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


}
相关推荐
伯远医学几秒前
Nat. Methods | 邻近标记技术:活细胞中捕捉分子互作的新利器
java·开发语言·前端·javascript·人工智能·算法·eclipse
RainCity几秒前
Java Swing 自定义组件库分享(五)
java·笔记·后端
woniu_buhui_fei4 分钟前
JVM垃圾回收
java·jvm
AC赳赳老秦8 分钟前
文案策划提效:OpenClaw批量生成活动文案、宣传海报配文,适配不同渠道调性
java·大数据·服务器·人工智能·python·deepseek·openclaw
wjs20249 分钟前
Matplotlib 轴标签和标题
开发语言
_codemonster13 分钟前
系统分析师系列目录
java·网络·数据库
XMYX-022 分钟前
27 - Go string 字符串处理与格式化:从底层原理到工程实践
开发语言·golang
赏金术士25 分钟前
Kotlin 协程面试题大全(Android 高频版)
android·开发语言·kotlin
带刺的坐椅27 分钟前
Spring AI 2.0 GA 倒计时:先别急,来看看 Java AI 框架的另一条路
java·spring·ai·llm·agent·solon
烟雨江南aabb32 分钟前
Python第四弹:python进阶-匿名函数和内置函数
开发语言·python