1、用到的包
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.support.CronTrigger; import java.util.concurrent.ScheduledFuture;
2、代码
@Configuration public class InventorySchedule { private static final Logger logger = LogManager.getLogger(InventorySchedule.class); @Autowired private ThreadPoolTaskScheduler threadPoolTaskScheduler; private ScheduledFuture<?> scheduledFuture; //定义定时任务 public void startCron(JSONObject cron){ try { //取出定时任务对象进行关闭,每次把之前的定时任务关闭,根据新的状态重新启用一次,达到最新配置 if (null != scheduledFuture){ scheduledFuture.cancel(true); } //将参数中时间转为 cron 表达式 例子为每天固定时间执行一次,根据需求修改String.format("%d %d %d ? * *") String cronStr = cron.getString("inventory_time"); String[] timeStramp = cronStr.split(":",-1); int second = Integer.parseInt(timeStramp[2]); int minute = Integer.parseInt(timeStramp[1]); int hour = Integer.parseInt(timeStramp[0]); String cronExpression = String.format("%d %d %d ? * *",second, minute, hour); //根据传入参数判断当前定时任务是否开启 SC.STATUS_1 为自定义常量 值为 1 if (cron.getString("inventory_status").equals(SC.STATUS_1)) { scheduledFuture = threadPoolTaskScheduler.schedule(new InventoryRunnable(),new CronTrigger(cronExpression)); } } catch (Exception e) { e.printStackTrace(); } } //线程池子线程 private static class InventoryRunnable implements Runnable { @Override public void run() { logger.debug("自动盘点执行时间" + new Date());、 } } }
3、调用
3.1 创建实例
@Configuration public class InventoryApiconfig { @Scope //单例模式调用 @Bean public InventorySchedule inventoryScheduleTask() { return new InventorySchedule(); } }
3.2 项目启动时自动调用一次
@Component @Order(1) public class AskForInventorySchedule implements ApplicationRunner { private static final Logger logger = LogManager.getLogger(AskForInventorySchedule.class); @Autowired private TIntelligentInventoryConfigMapper tIntelligentInventoryConfigMapper; @Autowired private InventoryApiconfig inventoryApiconfig; @Override public void run(ApplicationArguments args) { logger.info("SYS|RUN-INFO|启动定时盘点完成|"); //从数据库中查出 定时任务参数 JSONObject data = tIntelligentInventoryConfigMapper.selectInventoryConfig(); inventoryApiconfig.inventoryScheduleTask().startCron(data)); } }
3.3 定时任务配置变化时调用 (调用方式同3.2)
4、相关截图
数据库 定时任务启停状态,每天启动时间
5、相关链接