摘要
我们在项目中经常会处理一些定时更新的数据,比如定期删除缓存的token,设置订单的有效时间,利用定时任务处理日志及一些缓存,或者定期做更新数据等一系列的复杂业务;在这里我做了一份总结,希望能帮到大家;如果有不准确的地方希望能够提供宝贵的建议
代码下载地址:https://github.com/tazhigang/TimedTask.git
1、线程实现定时任务
话不多说,直接上代码
package com.ittzg.task;
/**
* @Author: ittzg
* @CreateDate: 2018/12/7
* @Description: 线程实现定时任务
* 运行环境是JDK8 使用lambda表达式 大家可以下去看看
*/
public class TimedTaskDemo01 {
public static void main(String[] args) {
new Thread(() ->{
int time = 1;
while(true){
//每5秒钟执行一次
System.out.println("Perform the task every 5 secouds!\t"+(time++)+"\t"+new Date());
try {
Thread.sleep(5000);} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
运行结果
Perform the task every 5 secouds! 1 Fri Dec 07 14:59:08 GMT+08:00 2018
Perform the task every 5 secouds! 2 Fri Dec 07 14:59:13 GMT+08:00 2018
Perform the task every 5 secouds! 3 Fri Dec 07 14:59:18 GMT+08:00 2018
......