• 2024Java springboot mybatis-flex 根据数据表时间开启定时任务


    1.数据表自定义的时间(我要11和00分开 )

    2.启动类添加定时任务逻辑

    1. @SpringBootApplication
    2. @MapperScan("com.test.mapper")
    3. // 开启定时任务
    4. @EnableScheduling
    5. public class TestApplication {
    6. //引入自己的mapper层或service层
    7. @Resource
    8. private SetUpMapper setUpMapper;
    9. public static void main(String[] args) {
    10. SpringApplication.run(TestApplication.class, args);
    11. }
    12. //定时任务 @PostConstruct不要丢了
    13. @PostConstruct
    14. public void scheduleTasks() {
    15. ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
    16. //获取时间点 11:00
    17. String morning = setUpMapper.selectOneById(5).getParameter().split("-")[1];
    18. //定时任务业务
    19. //获取小时11,Integer.parseInt(morning.split(":")[0]
    20. //获取分钟00,Integer.parseInt(morning.split(":")[1]
    21. //定时任务就是,1100分开启定时任务
    22. scheduler.schedule(() -> {
    23. //定时任务业务,这是 简单测试,到点打印下班啦
    24. System.ou.println("下班啦");
    25. }, getTimeUntilNextExecution(Integer.parseInt(morning.split(":")[0]), Integer.parseInt(morning.split(":")[1])), TimeUnit.SECONDS);
    26. /**
    27. * 计算距离下一个指定时间点的时间间隔(单位:秒)
    28. *
    29. * @param hour
    30. * @param minute
    31. * @return
    32. */
    33. private long getTimeUntilNextExecution(int hour, int minute) {
    34. Calendar now = Calendar.getInstance();
    35. Calendar nextExecutionTime = Calendar.getInstance();
    36. nextExecutionTime.set(Calendar.HOUR_OF_DAY, hour);
    37. nextExecutionTime.set(Calendar.MINUTE, minute);
    38. nextExecutionTime.set(Calendar.SECOND, 0);
    39. if (now.after(nextExecutionTime)) {
    40. // 如果当前时间已经过了指定时间点,则推迟到第二天
    41. nextExecutionTime.add(Calendar.DAY_OF_MONTH, 1);
    42. }
    43. return (nextExecutionTime.getTimeInMillis() - now.getTimeInMillis()) / 1000;
    44. }
    45. }

  • 相关阅读:
    JavaScript 实现每次循环都等待
    Hadoop——Yarn 调度器和调度算法
    云服务仿真:完全模拟 AWS 服务的本地体验 | 开源日报 No.45
    解决MySQL8.0本地计算机上的MySQL服务启动后停止没有报告任何错误
    Ignite实战
    android之TextView自由选择复制
    一个好的产品如何定义?
    CSS中的定位
    自定义表单系统开源是否好用?
    【实践篇】redis管道pipeline使用详解
  • 原文地址:https://blog.csdn.net/m0_47484034/article/details/138183263