Scheduled与CronTrigger的使用——阅读开源项目中的代码

一、定时任务:TimeTask,是一个抽象类,需要子类进行具体实现。

  (1)固定延时:基于上次任务的实际执行时间来计算,如果由于某种原因上次任务时间延迟了,则本次任务也会延时。如果初始时间为一个过去时间,任务立即执行

  (2)固定频率:基于初始时间到当前时间的差值来计算,所以会将丢失的次数尽量补回来。如果初始时间为过去时间,任务立即执行,并且会运行多次,弥补丢失的次数。

  (3)定时任务缺点:后台只有一个线程在运行;将定时任务设置为无限循环,导致死锁;一个任务的未处理异常导致所有的任务取消。固定频率会补齐丢失的次数。

TimeTask源码解析:解释固定延时与固定频率的处理原理

  参考博客:https://zhuanlan.zhihu.com/p/97859210

   

二、ScheduledExecutorService:弥补Timetask的问题,并且加入了线程池;同时对固定频率算法进行了改动,不支持以绝对时间作为初始时间。

具体用法略:

 

三、CronTrigger使用:

 

 

示例:

  1、设置定时任务:@Scheduled

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
设置延时任务
 */
@Service
public class ScheduleTaskService {
    private static final SimpleDateFormat FORMAT = new SimpleDateFormat("HH:mm:ss");

    //固定频率

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime(){
        System.out.println("每隔5秒执行一次:"+FORMAT.format(new Date()));
    }
    //固定延时
    @Scheduled(fixedDelay = 10000)
    public void delayExecuteTask(){
        System.out.println("延迟10秒后,每隔10秒执行一次");
    }

    //使用crontrigger(每天的17:50执行)
    @Scheduled(cron = "0 53 17 * * ?")
    public void fixTimeExecution(){
        System.out.println("在指定的时间:"+ FORMAT.format(new Date())+"执行");
    }

}

 

  2、spring容器开始计划任务支持:@EnableScheduling  

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@ComponentScan("com.yrc.scheduled")
@EnableScheduling       //开启计划任务
public class MyConfig {
}

  3、启动演示:

  

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    private static final SimpleDateFormat FORMAT = new SimpleDateFormat("HH:mm:ss");
    public static void main(String args[]){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
        ScheduleTaskService scheduleTaskService = context.getBean(ScheduleTaskService.class);
        System.out.println("当前时间:"+ FORMAT.format(new Date()));

    }
}

 

 

参考博客:https://blog.csdn.net/richard_666/article/details/89295460

 

posted @ 2020-05-22 17:17  怪兽不纯粹  阅读(458)  评论(0)    收藏  举报