private ThreadPoolTaskScheduler threadPoolTaskScheduler;
// 加载时创建定时器
{
threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
//初始化,
threadPoolTaskScheduler.initialize();
}
private ScheduledFuture<?> future;
// 定时器本体 开启定时器
public void setCron(final String cron) {
this.cron = cron;
stopCron();
future = threadPoolTaskScheduler.schedule(new Runnable() {
@Override
public void run() {
try {
//自己的 业务
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Trigger() {
public Date nextExecutionTime(TriggerContext triggerContext) {
if ("".equals(cron) || cron == null)
return null;
CronTrigger trigger = new CronTrigger(cron);// 定时任务触发,可修改定时任务的执行周期
Date nextExecDate = trigger.nextExecutionTime(triggerContext);
return nextExecDate;
}
});
}
// 关闭定时器
public void stopCron() {
if (future != null) {
future.cancel(true);
}
}