在Spring Boot中实现定时任务功能,可以通过Spring自带的定时任务调度,也可以通过集成经典开源组件Quartz实现任务调度。

一、Spring定时器

1、cron表达式方式

使用自带的定时任务,非常简单,只需要像下面这样,加上注解就好,不需要像普通定时任务框架那样继承任何定时处理接口 ,简单示例代码如下:

Spring Boot定时任务应用实践
package com.power.demo.scheduledtask.simple;

import com.power.demo.util.DateTimeUtil;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@EnableScheduling
public class SpringTaskA {

    /**
     * CRON表达式参考:http://cron.qqe2.com/
     **/
    @Scheduled(cron = "*/5 * * * * ?", zone = "GMT+8:00")
    private void timerCron() {

        try {
            Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(String.format("(timerCron)%s 每隔5秒执行一次,记录日志", DateTimeUtil.fmtDate(new Date())));

    }

}
Spring Boot定时任务应用实践

相关文章:

  • 2022-12-23
  • 2022-01-30
  • 2022-12-23
  • 2021-09-29
  • 2021-06-23
  • 2021-06-25
猜你喜欢
  • 2021-11-06
  • 2021-09-13
  • 2021-08-17
  • 2021-12-11
  • 2021-08-07
相关资源
相似解决方案