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


}
相关推荐
手揽回忆怎么睡几秒前
java打包无效的发行版:xx,临时修复当前窗口指定 JDK21
java·开发语言
Eric.Lee2021几秒前
python实现多个pdf合并
开发语言·python·pdf·pdf合并
一直有一个ac的梦想10 分钟前
cmu15445 2025fall lec15 query optimiaztion Pt1
java·服务器·数据库
郝学胜-神的一滴11 分钟前
干货版《算法导论》03:动态数组 × 链表的极致平衡艺术
java·数据结构·c++·python·算法·链表
SamDeepThinking13 分钟前
IntelliJ IDEA 中有什么让你相见恨晚的技巧?
java·后端·程序员
SamDeepThinking15 分钟前
为什么选微服务而不是动态扩容单体
java·后端·架构
xyq202415 分钟前
Highcharts 曲线图:深度解析与实战应用
开发语言
顾温18 分钟前
协程结束——实测
开发语言·unity·c#
小新同学^O^23 分钟前
初步了解--> SpringCloud
java·学习·spring·spring cloud
ch.ju40 分钟前
Java程序设计(第3版)第二章——函数的递归
java·开发语言