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

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

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

复制代码
@SpringBootApplication
@MapperScan("com.test.mapper")
// 开启定时任务
@EnableScheduling
public class TestApplication {
    //引入自己的mapper层或service层
    @Resource
    private SetUpMapper setUpMapper;

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

    //定时任务  @PostConstruct不要丢了
    @PostConstruct
    public void scheduleTasks() {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
        //获取时间点 11:00
        String morning = setUpMapper.selectOneById(5).getParameter().split("-")[1];

         //定时任务业务
        //获取小时11,Integer.parseInt(morning.split(":")[0] 
         //获取分钟00,Integer.parseInt(morning.split(":")[1] 
          //定时任务就是,11点00分开启定时任务
        scheduler.schedule(() -> {
            //定时任务业务,这是 简单测试,到点打印下班啦
           System.ou.println("下班啦");
        }, getTimeUntilNextExecution(Integer.parseInt(morning.split(":")[0]), Integer.parseInt(morning.split(":")[1])), TimeUnit.SECONDS);

       

    /**
     * 计算距离下一个指定时间点的时间间隔(单位:秒)
     *
     * @param hour
     * @param minute
     * @return
     */
    private long getTimeUntilNextExecution(int hour, int minute) {
        Calendar now = Calendar.getInstance();
        Calendar nextExecutionTime = Calendar.getInstance();
        nextExecutionTime.set(Calendar.HOUR_OF_DAY, hour);
        nextExecutionTime.set(Calendar.MINUTE, minute);
        nextExecutionTime.set(Calendar.SECOND, 0);

        if (now.after(nextExecutionTime)) {
            // 如果当前时间已经过了指定时间点,则推迟到第二天
            nextExecutionTime.add(Calendar.DAY_OF_MONTH, 1); 
        }

        return (nextExecutionTime.getTimeInMillis() - now.getTimeInMillis()) / 1000;
    }


}
相关推荐
captain3767 小时前
MyBatis操作数据库(入门2)
java·数据库·spring boot·后端·spring·mybatis
呆呆虫127 小时前
用 orjson 加速 SerpBase 响应解析:基准对比与注意事项
开发语言·php
心中有你02148 小时前
Java实现Dijkstra最短路径算法(邻接表 + 优先队列)
java·数据库·算法
心疼你的一切8 小时前
Python自动发邮件实战定时发报表
大数据·开发语言·python
步行cgn8 小时前
Spring MVC + Thymeleaf 模板解析失败:从 500 错误到页面正常显示
java·spring·mvc
lgcgkCQ9 小时前
【AI 转型实战 1】SpringAI 入门:搭建基础大模型对话能力
java·ai·agent·rag·spring ai·mcp·langchain4j
Wang's Blog9 小时前
Java 项目实战:交友项目 - 用户体系集成总结
java·开发语言·交友
学到老活到老9 小时前
第 24 集:配置文件写了 80,Spring Boot 为什么读到 90?
java·后端·spring
tongyiixiaohuang9 小时前
供应商主数据同步实战:从易快报到金蝶云星空的单一策略落地
java·网络·数据库
中科三方9 小时前
IPv6检测常见问题:AAAA记录检测不通过是什么原因?
开发语言·php