中国建设银行网站包头分行,小程序游戏制作平台,微豆网络科技有限公司网页设计,包头网站优化spring根据定时任务的特征#xff0c;将定时任务的开发简化到了极致。怎么说呢#xff1f;要做定时任务总要告诉容器有这功能吧#xff0c;然后定时执行什么任务直接告诉对应的bean什么时间执行就行了#xff0c;就这么简单#xff0c;一起来看怎么做
步骤①#xff1a;…spring根据定时任务的特征将定时任务的开发简化到了极致。怎么说呢要做定时任务总要告诉容器有这功能吧然后定时执行什么任务直接告诉对应的bean什么时间执行就行了就这么简单一起来看怎么做
步骤①开启定时任务功能在引导类上开启定时任务功能的开关使用注解EnableScheduling
SpringBootApplication
//开启定时任务功能
EnableScheduling
public class Springboot22TaskApplication {public static void main(String[] args) {SpringApplication.run(Springboot22TaskApplication.class, args);}
}步骤②定义Bean在对应要定时执行的操作上方使用注解Scheduled定义执行的时间执行时间的描述方式还是cron表达式
Component
public class MyTask {Scheduled(cron 0/1 * * * * ?)public void print(){System.out.println(Thread.currentThread().getName() :spring task run...);}
}完事这就完成了定时任务的配置。总体感觉其实什么东西都没少只不过没有将所有的信息都抽取成bean而是直接使用注解绑定定时执行任务的事情而已。
如何想对定时任务进行相关配置可以通过配置文件进行不是必须的
spring:task:scheduling:pool:size: 1 # 任务调度线程池大小 默认 1thread-name-prefix: ssm_ # 调度线程名称前缀 默认 scheduling- shutdown:await-termination: false # 线程池关闭时等待所有任务完成await-termination-period: 10s # 调度线程关闭前最大等待时间确保最后一定关闭定时过程中需要写cron表达式非常麻烦。这里提供一个在线cron表达式生成器可以根据你指定的时间生成非常方便。 如果指定任务为每小时执行一次同时又要在每天早上8点执行一次其他操作可以通过LocalDataTime进行时间判断执行
Component
public class MyTask {Scheduled(cron 0/1 * * * * ?)public void print(){LocalDateTime now LocalDateTime.now();int hour now.getHour();System.out.println(Thread.currentThread().getName() :spring task run...);if(hour8){System.out.println(执行其他任务)}}
}