来来来小伙伴们,基于上篇的邮件服务,定时任务就不单独分项目了,天然整合进了邮件服务中。
不知道,大家在工作之中,经常会用到那些定时任务去执行特定的业务,这里列举一下我在工作中曾经使用到的几种实现。
任务介绍
项目应用
创建任务
代码中,可以发现,sendMail方法上注解被注释掉了,目前我们采用的是xml配置实现的。
import org.springframework.stereotype.Component;
/**
 * 统计失败邮件定时重新发送
 * 创建时间 2017年7月21日
 *
 */
@Component("sendMail")
public class SendMail {
 //@Scheduled(cron = "0/5 * * * * ?")
 public void sendMail() {
  System.out.println("统计失败邮件定时重新发送开始");
 }
}
配置文件
<!-- 配置任务线性池 --> <task:executor id="executor" pool-size="5" /> <task:scheduler id="scheduler" pool-size="5"/> <!-- 启用注解驱动的定时任务 --> <task:annotation-driven executor="executor" scheduler="scheduler" proxy-target-class="true"/> <task:scheduled-tasks scheduler="scheduler"> <!-- 统计失败邮件定时重新发送 --> <task:scheduled ref="sendMail" method="sendMail" cron="0/5 * * * * ?"/> </task:scheduled-tasks>
启动项目
/**
 * 启动类
 * 创建时间 2017年7月19日
 *
 */
@EnableAutoConfiguration
@ComponentScan(basePackages={"com.itstyle.main"})
@ImportResource({"classpath:spring-context-dubbo.xml","classpath:spring-context-task.xml"})
public class Application {
 private static final Logger logger = Logger.getLogger(Application.class);
 public static void main(String[] args) throws InterruptedException {
  SpringApplication.run(Application.class, args);
  logger.info("项目启动 ");
 }
}
启动后,控制台会每5s打印”统计失败邮件定时重新发送开始”。当然Scheduled的功能不仅仅如此,我们查找源码Scheduled类,可以发现还有一些注解属性,这里就不一一为大家介绍了。总之,要养成查看源码API的习惯。
@Target({ java.lang.annotation.ElementType.METHOD,
  java.lang.annotation.ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {
 public abstract String cron();
 public abstract String zone();
 public abstract long fixedDelay();
 public abstract String fixedDelayString();
 public abstract long fixedRate();
 public abstract String fixedRateString();
 public abstract long initialDelay();
 public abstract String initialDelayString();
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎点击右下角反馈进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。