来来来小伙伴们,基于上篇的邮件服务,定时任务就不单独分项目了,天然整合进了邮件服务中。
不知道,大家在工作之中,经常会用到那些定时任务去执行特定的业务,这里列举一下我在工作中曾经使用到的几种实现。
任务介绍
项目应用
创建任务
代码中,可以发现,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();
}
项目:spring-boot-mail_jb51.rar
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。