关于java:十分钟教你玩转SprintBoot定时任务

罕用的定时工作有两种:

  1. 基于注解
  2. 基于接口

基于注解@Scheduled


@Service
public class Scheduling1Service {

    //每2秒执行一次(若上次工作执行工夫超过2秒,则立刻执行,否则从上一个工作开始时算起2秒后执行本次工作)
    @Scheduled(fixedRate = 2000)
    public void test1() throws InterruptedException {
        Thread.sleep(1000L);//模仿定时工作执行消耗了1s
        Thread.sleep(3000L);//模仿定时工作执行消耗了3s
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date)+"==>SchedulingService.test1 is called");
    }

    //上一个工作执行完2秒后,再执行本次工作
    @Scheduled(fixedDelay = 2000)
    public void test2() throws InterruptedException {
        Thread.sleep(3000L);//模仿定时工作执行消耗了3s
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date)+"==>SchedulingService.test2 is called");
    }

    //反对corn表达式
    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点执行
    public void test3() throws InterruptedException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date)+"==>SchedulingService.test3 is called");
    }
}

注:不会写corn表达式的小伙伴,能够应用这个哦:https://cron.qqe2.com 会帮你主动生成corn表达式,且能检测你的表达式是否非法。十分好用!

以上三种是应用频次比拟多的。因为不承受参数,次要用户定时同步第三方根底数据的业务场景。

应用@Scheduled需在pom中援用springboot的相干依赖,并在Application主入口函数中减少@EnableScheduling的注解。

基于接口模式的定时工作

基于注解的形式的工作配置起来很简略也很好用,然而因为不能传递参数,应用场景无限。那么就须要应用基于接口模式的定时工作了。

增加依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
@Service
public class Scheduling3Service implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(
                new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("cccccccc");
                    }
                },
                triggerContext -> {
                    return new CronTrigger("0/1 * * * * ? ").nextExecutionTime(triggerContext);
                }
        );
    }
}

以上就是两种罕用的定时工作,小伙伴们,你,学废了吗?

更多java原创浏览:https://javawu.com

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理