タイミングタスク実行時間の動的変更
2882 ワード
データベースがタイミング実行時間を変更すると、プロジェクトを再起動することなく有効になります.次のクラスは、スレッドプールThreadPoolTaskSchedulerを使用してタスクサイクル実行を開始します.
定時タスクを書き直し、5秒ごとにデータベースの値を問い合わせる(ここではデータベースの値が自分でメンテナンスしているわけではないので、データベースがいつ変化するか分からないので、この方法しか使えません.自分でメンテナンスしているデータベースであれば、次の定時タスクはまったく必要ありません.プロジェクトの開始後とデータベースの更新後に上のstart()を呼び出します.方法:
参照先:http://www.pianshen.com/article/496033667/
package com.wuychn.task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import java.util.concurrent.ScheduledFuture;
/**
* @description ,
* @author wuyong
* @date 2019-10-23 10:22:49
* @Version V1.0
*/
@Configuration
public class FirstNurseTaskConfig {
@Autowired
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
private ScheduledFuture> scheduledFuture = null;
public void start(String cron) {
if (StringUtils.isNotBlank(cron)) {
//
if (scheduledFuture != null) {
scheduledFuture.cancel(true);
}
//
String[] times = cron.split(":");
assert times.length == 2;
//
int hours = Integer.parseInt(times[0]);
//
int minute = Integer.parseInt(times[1]);
// cron
cron = String.format("0 %s %s ? * *", minute, hours);
scheduledFuture = threadPoolTaskScheduler.schedule(() -> System.out.println("do sth"), new CronTrigger(cron));
}
}
}
定時タスクを書き直し、5秒ごとにデータベースの値を問い合わせる(ここではデータベースの値が自分でメンテナンスしているわけではないので、データベースがいつ変化するか分からないので、この方法しか使えません.自分でメンテナンスしているデータベースであれば、次の定時タスクはまったく必要ありません.プロジェクトの開始後とデータベースの更新後に上のstart()を呼び出します.方法:
package com.wuychn.task;
import com.wuychn.mapper.CronMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
/**
* @description TODO
* @author wuyong
* @date 2019-10-23 10:46:59
* @Version V1.0
*/
@Configuration
@EnableScheduling
public class CheckCronTask {
@Autowired
private CronMapper cronMapper;
private String cron = null;
@Autowired
private FirstNurseTaskConfig firstNurseTaskConfig;
// 5
@Scheduled(cron = "0/5 * * * * ?")
public void checkCron() {
// newCron :HH:mm
String newCron = cronMapper.getCron();
if (StringUtils.isNotBlank(newCron)) {
if (StringUtils.isBlank(cron) || !cron.equalsIgnoreCase(newCron)) {
cron = newCron;
firstNurseTaskConfig.start(cron);
}
}
}
}
参照先:http://www.pianshen.com/article/496033667/