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;
    }


}
相关推荐
洛阳泰山几秒前
【开源项目】MaxKB4J基于java开发的工作流和 RAG智能体的知识库问答系统
java·人工智能
IT-ZXT8884 分钟前
Spring 框架之IOC容器加载重要组件
java·后端·spring
Jay_2717 分钟前
python项目如何创建docker环境
开发语言·python·docker
xlsw_24 分钟前
MyBatis之测试添加功能
java·开发语言·mybatis
忘梓.34 分钟前
从二叉树到 STL:揭开 set 容器的本质与用法
开发语言·c++
爬虫程序猿40 分钟前
利用 Python 爬虫获取淘宝商品详情
开发语言·爬虫·python
保持学习ing1 小时前
黑马Java面试笔记之 消息中间件篇(RabbitMQ)
java·微服务·面试·java-rabbitmq
---wzy---1 小时前
docker生命周期
java·docker·容器
曹勖之1 小时前
在MATLAB中使用自定义的ROS2消息
开发语言·matlab·机器人·ros·simulink·ros2
可可,天上人间1 小时前
path环境变量
java·环境·环境变量·path