Spring boot运行时添加定时任务

来源:互联网 发布:在线数据图表处理软件 编辑:程序博客网 时间:2024/06/07 20:28

最近在做一个Web的时候,因为定时的时间是由需要在网站运行时动态添加定时任务.

并且所需要的定时任务还不少,且错综复杂.

一开始去网上找资料,

@Componentpublic class ScheduledTask {    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    private Integer count0 = 1;    private Integer count1 = 1;    private Integer count2 = 1;    @Scheduled(fixedRate = 5000)    public void reportCurrentTime() throws InterruptedException {        System.out.println(String.format("---第%s次执行,当前时间为:%s", count0++, dateFormat.format(new Date())));    }    @Scheduled(fixedDelay = 5000)    public void reportCurrentTimeAfterSleep() throws InterruptedException {        System.out.println(String.format("===第%s次执行,当前时间为:%s", count1++, dateFormat.format(new Date())));    }    @Scheduled(cron = "0 0 1 * * *")    public void reportCurrentTimeCron() throws InterruptedException {        System.out.println(String.format("+++第%s次执行,当前时间为:%s", count2++, dateFormat.format(new Date())));    }}
是能用,但是着是基于注解的,一开始就要用代码写死了,很明显不符合在"运行时"添加定时任务.
package com.jege.spring.boot.task;import java.text.SimpleDateFormat;import java.util.Date;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.scheduling.Trigger;import org.springframework.scheduling.TriggerContext;import org.springframework.scheduling.annotation.SchedulingConfigurer;import org.springframework.scheduling.config.ScheduledTaskRegistrar;import org.springframework.scheduling.support.CronTrigger;import org.springframework.stereotype.Component;import com.jege.spring.boot.data.jpa.entity.User;import com.jege.spring.boot.data.jpa.repository.UserRepository;/** * 动态修改定时任务cron参数 */@Componentpublic class DynamicScheduledTask implements SchedulingConfigurer {  private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");  private static final String DEFAULT_CRON = "0/5 * * * * ?";  private String cron = DEFAULT_CRON;  @Autowired  private UserRepository userRepository;  @Override  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {    taskRegistrar.addTriggerTask(new Runnable() {      @Override      public void run() {    if (!cron.equals(DEFAULT_CRON)) {      User user = new User("je_ge", 20);      userRepository.save(user);    }    // 定时任务的业务逻辑    System.out.println("动态修改定时任务cron参数,当前时间:" + dateFormat.format(new Date()));      }    }, new Trigger() {      @Override      public Date nextExecutionTime(TriggerContext triggerContext) {    // 定时任务触发,可修改定时任务的执行周期    CronTrigger trigger = new CronTrigger(cron);    Date nextExecDate = trigger.nextExecutionTime(triggerContext);    return nextExecDate;      }    });  }  public void setCron(String cron) {    this.cron = cron;  }}
这个也能用,我刚开始还打算采取了这个办法作为本次设计的定时任务,结果在做的过程中发现:

1.这样的定时也是在一开始就要设定的(configureTasks这个方法只会运行一次),后面没办法添加定时任务了

2.这个定时,如果你要修改定时的时间的话,前提条件是在你修改了定时时间后,这个定时任务必须运行定时方法后,才能修改定时任务.

比如在configureTask里面添加几个定时任务,是15分钟之后执行定时方法的,但是用户突然又要设置12分钟之后的时间来执行定时方法,那么就会出现这个定时任务在15分钟之后执行完定时方法之后才改变了定时时间(刚才的12分钟)

这样当然也不符合我们的需求

后面找了一个方法,代码如下:

/** * Created by 我码故我在 on 17-5-5. */@Componentpublic class TestSchedule implements SchedulingConfigurer {    private ThreadPoolTaskScheduler mScheduler = new ThreadPoolTaskScheduler(); //可以动态往里面添加定时任务    private Map<String, ScheduledFuture> map = new HashMap<>();    Runnable run = new Runnable() {        @Override        public void run() {            //TODO:JOB            System.out.println("MyJob");        }    };    @Override    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {        mScheduler.initialize();    }    public void setScheduler(String jobName, String cronExp) {        map.put(jobName, mScheduler.schedule(run, new CronTrigger(cronExp)));    }}

只要在运行时,调用testSchedule.setScheduler("MyFirstJob", "0 0 1 1,7 * ? ");cron表达式换成所需要的就好,就可以把定时任务添加进去,等待执行定时方法.

引用:

第一个代码段

第二个代码段

0 1
原创粉丝点击