(1)在Spring的配置文件中添加定时任务相关配置:
xml配置的头文件中添加:
xmlns:task="http://www.springframework.org/schema/task"
以及在xsi:schemaLocation中添加:
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd
最后添加:
其中,这里首先定义了Spring自动扫描定时任务所在的package,也就是“cn.zifangsky.task”。接着定义了两个线程池以及启用定时任务的扫描机制
(2)添加测试任务:
package cn.zifangsky.task;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class SimpleSpringTask {
/**
* 每次任务执行完之后的2s后继续执行
*/
@Scheduled(fixedDelay=2000)
public void say(){
Date current = new Date();
Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("--------" + format.format(current) + "---------");
}
/**
* 0分的时候打印
*/
@Scheduled(cron="0 * * * * ?")
public void print(){
System.out.println("当前是整分!!!");
}
}
上面第一个任务定义了每个任务执行完之后的2s之后再次执行,如果需要强制指定每隔多少时间执行一次任务,可以将上面的fixedDelay改成fixedRate,如:
/**
* 每隔两秒执行一次本方法
*/
@Scheduled(fixedRate=2000)
public void say(){
Date current = new Date();
Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("--------" + format.format(current) + "---------");
}
当然,上面的第二种任务形式类似于Linux下的crontab定时任务,几个参数位分别表示:分钟、小时、天(每月中的天)、月份以及星期。最后的那个问号毫无疑问就表示使用@Scheduled注解标注的本个方法了
注:如果想要了解更多的关于Linux中使用crontab命令的用法可以参考我的这篇文章:https://www.zifangsky.cn/591.html
(3)测试:
运行这个项目后,最后控制台中的输出如下:
注:上面的水印是我的个人博客。由于题主的问题不是一两句文字可以描述清楚地,因此引用了我博客中的内容,请审核人员手下留情
PS:如果觉得对你有所帮助的话,望采纳!!!