@Service
public class SchedulerJob {
private static final Logger logger = LoggerFactory.getLogger(SchedulerJob.class);
private static final int POOL_SIZE = 20;
private static final ScheduledExecutorService EXECUTOR = new ScheduledThreadPoolExecutor(POOL_SIZE,
new ThreadFactoryBuilder().setNameFormat("job-pool-%d").build(),(r, executor) -> {
logger.error("SchedulerJob.task reject");
});
private static final Map<String, ScheduledFuture<?>> SCHEDULED_MAP = new ConcurrentHashMap<>();
/**
* 使用cronExpression 任务将会在指定cronExpression的下个周期执行
*/
public void test(String expression, Integer jobId, Integer status) {
// 校验使用quartz-2.3.2.jar中的工具类CronExpression
boolean validExpression = CronExpression.isValidExpression(expression);
if (!validExpression) {
logger.error("cron expression error, expression: {}", expression);
return;
}
TaskScheduler scheduler = new ConcurrentTaskScheduler(EXECUTOR);
Trigger trigger = new CronTrigger(expression, TimeZone.getTimeZone(ZoneId.systemDefault()));
String key = expression + "-" + jobId;
boolean exist = SCHEDULED_MAP.containsKey(key);
if (exist) {
// 任务已存在
if (status == 1) {
// 停止任务
ScheduledFuture<?> scheduledFuture = SCHEDULED_MAP.get(key);
scheduledFuture.cancel(false);
if (scheduledFuture.isCancelled()) {
SCHEDULED_MAP.remove(key);
logger.info("任务已停止,jobKey:{}", key);
}
}
} else {
ScheduledFuture<?> schedule = scheduler.schedule(new FunTask(jobId), trigger);
SCHEDULED_MAP.put(key, schedule);
}
}
/**
* 按给定周期执行-立即执行(单位秒)
*/
public void test(long period, Integer jobId, Integer status) {
TaskScheduler scheduler = new ConcurrentTaskScheduler(EXECUTOR);
String key = period + "-" + jobId;
boolean exist = SCHEDULED_MAP.containsKey(key);
if (exist) {
// 任务已存在
if (status == 1) {
// 停止任务
ScheduledFuture<?> scheduledFuture = SCHEDULED_MAP.get(key);
scheduledFuture.cancel(false);
if (scheduledFuture.isCancelled()) {
SCHEDULED_MAP.remove(key);
logger.info("任务已停止,jobKey:{}", key);
}
}
} else {
ScheduledFuture<?> schedule = scheduler.scheduleAtFixedRate(new FunTask(jobId), period * 1000);
SCHEDULED_MAP.put(key, schedule);
}
}
private static class FunTask implements Runnable {
private final Integer jobId;
private FunTask(Integer jobId) {
this.jobId = jobId;
}
@Override
public void run() {
logger.info("jobId:{},executor...", jobId);
}
}
}
使用spring实现定时任务
最新推荐文章于 2021-11-14 15:19:44 发布