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


}
相关推荐
黎宇幻生2 小时前
Java全栈学习笔记39
java·笔记·学习
Aurorar0rua3 小时前
C Primer Plus Notes 09
java·c语言·算法
nongcunqq4 小时前
abap 操作 excel
java·数据库·excel
R-G-B5 小时前
【02】C#入门到精通——C# 变量、输入/输出、类型转换
开发语言·c#·c# 变量·c#输入/输出·c#类型转换
星河队长5 小时前
C# 软件加密方法,有使用时间限制,同时要防止拷贝
开发语言·c#
史迪奇_xxx5 小时前
10、一个简易 vector:C++ 模板与 STL
java·开发语言·c++
2301_801252225 小时前
Java中的反射
java·开发语言
Kiri霧5 小时前
Rust开发环境搭建
开发语言·后端·rust
weixin-a153003083165 小时前
[数据抓取-1]beautifulsoup
开发语言·python·beautifulsoup
遇印记6 小时前
大二java学习笔记:二维数组
java·笔记·学习