Quartz Scheduler Trigger动态更新任务触发器时间间隔

package com.xxxxx.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hebyl.ccp.framework.util.QueryUtil;
import com.hebyl.siccpzdycdy.config.QuartzConfig;
import lombok.SneakyThrows;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

public class UpdateApplicationResultTask extends QuartzJobBean {

    private static final int EXPIRED_DAYS = 3; // 设置超过的天数,这里假设为3天

  

    @Autowired
    private Scheduler scheduler;


    @SneakyThrows
    @Override
    protected synchronized void executeInternal(JobExecutionContext context) throws JobExecutionException {
       //--------业务逻辑----------
        // 重新计算并更新Trigger的时间间隔
        updateTriggerInterval();    
    }

//   

    private synchronized void updateTriggerInterval() throws SchedulerException {
        //此方法可以换成你的计算下次执行时间方法
        Integer newInterval = greenApplicationService.getInitialInterval();
        TriggerKey triggerKey = new TriggerKey("updateApplicationResultTrigger");
        Trigger existingTrigger = scheduler.getTrigger(triggerKey);
        // 计算下一次执行时间
        long nextFireTime = System.currentTimeMillis() + (newInterval * 1000L);
        System.out.println("下次执行时间" + new Date(nextFireTime));
        if (existingTrigger!= null) {
            TriggerBuilder tb = existingTrigger.getTriggerBuilder();
            Trigger newTrigger =  tb.withSchedule(SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(newInterval)
                    .withRepeatCount(1)
                    .repeatForever())
                    .startAt(new Date(nextFireTime))
                    .build();      
                    //更新任务    
            scheduler.rescheduleJob(existingTrigger.getKey(), newTrigger);
        }
    }
}


//暂时方法放到这
 /**
     * 获取时间间隔(定任务用)
     * @author yangjianbing
     * @date 2024-11-06 17:22
     */
    public Integer getInitialInterval(){
        Integer IntervalIn=10;//一分钟
            // 获取当前时间
            LocalDateTime currentDateTime = LocalDateTime.now();
            // 获取下次执行时间//这里好像可以直接用,在优化吧。
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime localDateTime = LocalDateTime.parse(greenApplicationDAO.getReleaseTime(), formatter);
            localDateTime = localDateTime.plusDays(3);
            // 计算时间间隔(以分钟为单位)
            Duration duration = Duration.between(currentDateTime,localDateTime);//三天后日期减去现在日期
            long minutes = duration.toMinutes()+1;//加一分钟
            IntervalIn=(int) Math.min(Integer.MAX_VALUE, minutes)*60;
            if (IntervalIn<=0){
                IntervalIn=10;//下次间隔时间一分钟
            }
        return IntervalIn;
    }
//配置类
package com.xxxx.config;
;

import com.hebyl.siccpzdycdy.task.UpdateApplicationResultTask;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class QuartzConfig {

   

    @Bean
    public JobDetail updateApplicationResultJobDetail() {
        return JobBuilder.newJob(UpdateApplicationResultTask.class)//任务类名字
                .withIdentity("updateApplicationResultJob")
                .storeDurably()
                .build();
    }

    /**
     * 触发规则
     * @author yangjianbing
     * @date 2024-11-06 17:30
     */
    @Bean
    public Trigger updateApplicationResultTrigger() {

        JobDetail jobDetail = updateApplicationResultJobDetail();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        jobDataMap.put("triggerKey", new TriggerKey("updateApplicationResultTrigger"));

        //删除了greenApplicationService。方法上面有
        Integer intervalIn = greenApplicationService.getInitialInterval();//间隔时间

        System.out.println("下次间隔秒" + intervalIn);
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInSeconds(intervalIn)//秒
                .withRepeatCount(1)
                .repeatForever();
        org.quartz.Trigger newTrigger=TriggerBuilder.newTrigger()
                .forJob(updateApplicationResultJobDetail())
                .withIdentity("updateApplicationResultTrigger")
                .withSchedule(scheduleBuilder)
                .build();
        return newTrigger;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值