
在某些业务场景中,要在特定的时间去执行一些任务,比如:定时修改项目中的订单状态,定时在某个时间发送邮件,这时就需要用到定时任务。
Timer在java中一个完整的定时任务可以用Timer和TimerTask两个类配合完成。
Timer是一种工具,线程用其安排在后台线程中执行的任务,可安排任务执行一次或者定期重复执行。
TimerTask是由Timer安排执行一次或者重复执行的任务。
Timer中提供了四个方法:
(1)schedule(TimerTask task,Date time)——安排在指定的时间执行指定的任务
(2)schedule(TimerTask task,Date firstTime,long period)——安排指定的任务在指定的时间开始进行重复的固定延迟执行
(3)schedule(TimerTask task,long delay)——安排在指定延迟后执行指定的任务
(4)schedule(TimerTask task,long delay,long period)——安排指定的任务在指定的延迟后开始进行重复的固定速率执行
这里就用我在项目中遇到的案例来演示:
分析:在满足一定时间后自动的去修改当前任务的状态,当然在这里需要写它的接口和实现方法,以及满足当前定时任务的SQL,当它在项目中的某个模块中存在多少时间后,我们没有去处理它,就自动修改它的状态。
public void autorelease(OrderInformation order);
实现接口,这了可根据自己的项目来实现
@Override
@Transactional
public void autorelease(OrderInformation order) {
//selectClaimTime 查询的是满足对应SQL的列表
List list = orderMapper.selectClaimTime(order);
//循环遍历
for (OrderInformation orderInformation : list) {
AccountInformation account = new AccountInformation();
account.setId(orderInformation.getAccountId());
//拿到订单的认领时间
long time = orderInformation.getClaimTime().getTime();
Date date = new Date();
long time1 = date.getTime();//当前时间
long l = time1 - time;//相差时间
//如果当前的时间-认领的时间大于12小时,就执行下面
if (l>=12*60*60*1000L){
//修改任务状态---0
orderInformation.setTaskStatus("0");
orderMapper.releaseClaim(orderInformation);
//修改账号状态---0
account.setAccountStatus("0");
accountMapper.updateAccountStatus(account);
}
}
}
public List selectClaimTime(OrderInformation order);
这里SQL就不写出来了,可根据自己的表结构来写。
在创建一个类作为定时任务,实现ApplicationRunner
这里实现了ApplicationRunner接口,是因为这个定时任务是我们在启动服务后,才去执行,对应的我们需要在启动类上面添加一个注解@EnableScheduling
@Component
@Slf4j
public class AfterServiceStarted implements ApplicationRunner {
@Autowired
private IOrderService orderService;
//五分钟
private static final Long PERIOD = 1000L * 60 * 5;
@Override
public void run(ApplicationArguments args) {
Timer timer = new Timer(true);
timer.schedule(new TimerTask() {
@Override
public void run() {
//这里执行业务逻辑
orderService.autorelease(new OrderInformation());
}
//现在的时间,每隔五分钟执行一次
},new Date(),PERIOD);
}
}
到这里Timer定时任务就算完成了。
总结的不是很好,也是第一次写,还希望大家多多包涵!!!
谢谢!