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


}
相关推荐
devnullcoffee10 小时前
亚马逊 Buy Box 数据采集完全指南(2026):Python 实战 + Pangolinfo API
开发语言·python·亚马逊数据采集·亚马逊数据 api·pangolinfo api·亚马逊 buy box 数据·亚马逊数据采集软件
sleven fung10 小时前
Whisper库
开发语言·人工智能·python·算法·ai·whisper
天若有情67310 小时前
【C++趣味实战】仿写Burp代理逻辑!自定义可控迭代器:拦截Intercept/放行Forward/重放Repeater全实现
java·开发语言·c++
l1t10 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程37-38
开发语言·python
迷藏49410 小时前
Python+DuckDB:轻量级BI流水线实战
java·开发语言·python·原型模式
磊 子10 小时前
C++function与bind绑定器讲解
java·jvm·c++
咋吃都不胖lyh10 小时前
短期记忆和长期记忆都存 MySQL
android·java·开发语言
浮游本尊11 小时前
前端vue转后端java学习路径
java·前端·vue.js
KWTXX11 小时前
vibe coding-提示词
java·前端·算法
rime_neko11 小时前
js学习笔记
开发语言·前端·javascript