16点睛Spring4.1-TaskScheduler
程序员文章站
2022-03-10 11:30:55
...
16.1 TaskScheduler
- 提供对计划任务提供支持;
- 使用@EnableScheduling开启计划任务支持
- 使用@Scheduled来注解计划任务的方法;
16.2 示例
演示后台间断执行任务和定时计划任务
16.2.1 计划任务的配置
@Configuration
@EnableScheduling
public class DemoConfig {
}
16.2.2 计划配置任务类
package com.wisely.task.scheduler;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class DemoScheduledTask {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000) //每五秒执行一次
public void reportCurrentTime() {
System.out.println("每隔五秒执行一次 " + dateFormat.format(new Date()));
}
@Scheduled(cron = "0 22 11 ? * *" ) //每天上午11点22执行
public void fixTimeExecution(){
System.out.println("在指定时间 " + dateFormat.format(new Date())+"执行");
}
}
16.2.3 测试
package com.wisely.task.scheduler;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
@SuppressWarnings({ "unused", "resource" })
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext("com.wisely.task.scheduler");
}
}
输出结果
每隔五秒执行一次 11:21:42
每隔五秒执行一次 11:21:47
每隔五秒执行一次 11:21:52
每隔五秒执行一次 11:21:57
在指定时间 11:22:00执行
每隔五秒执行一次 11:22:02
新书推荐《JavaEE开发的颠覆者: Spring Boot实战》,涵盖Spring 4.x、Spring MVC 4.x、Spring Boot企业开发实战。
京东地址:http://item.jd.com/11894632.html
当当地址:http://product.dangdang.com/23926195.html
亚马逊地址:http://www.amazon.cn/图书/dp/B01D5ZBFUK/ref=zg_bsnr_663834051_6
淘宝地址:https://item.taobao.com/item.htm?id=528426235744&ns=1&abbucket=8#detail
或自己在京东、淘宝、亚马逊、当当、互动出版社搜索自选。
推荐阅读
-
Intel 16核心i9-7960X性能首曝:跑分只和Core i9-7900X打平?
-
Ubuntu16下Hive 安装
-
Redmi Note 8 Pro《魔兽世界》限定套装10月16日开售:限量5000部
-
C#基础概念二十五问 16-20
-
三星打响第一枪:今年旗舰手机内存都会从16GB起跳
-
16款2019旗舰机拍照盲测:iPhone11 Pro首轮被一加KO、三星Note10+最终称王
-
ipod touch5 16g和32g哪个好?苹果ipod touch5 16g和32g有什么区别?
-
怎样使用人生日历开抢16号返程票
-
推荐 16 款很棒的文本编辑器
-
SK海力士冲击16层堆叠内存:1平方毫米打10万个孔