Spring Boot 使用定时任务

前言

在实际开发中可能会需要使用到定时任务来完成业务需求。例如:项目部署后,需要在每天凌晨 1 点时统计数据记录到数据库中。

这个时候可以使用 Spring Boot 提供的定时任务完成需求,使用注解 @Scheduled 以及 cron 表达式即可。

使用

  1. 新建 Spring Boot 项目
  2. 在启动类上使用注解@EnableScheduling
@SpringBootApplication
@EnableScheduling
public class ScheduledDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScheduledDemoApplication.class, args);
    }

}
  1. 新建一个定时任务类 TimedTask,交给 Spring Boot 管理,使用注解 @Component
  2. 声明一个方法,使用注解 @Scheduled,设置注解属性 cron 的值,设定定时任务的执行规则。此处笔者声明一个方法,每5秒执行一次,打印方法执行时的时间。

注意 Spring Boot 中的 cron 表达式与 Linux 不同。

Linux 的 cron 表达式为 * * * * * * *,总共 7 个域,分别对应: 秒 分 时 天 月 周 年

Spring 的 cron 表达式为 * * * * * *,总共 6 个域,分别对应: 秒 分 时 天 月 周。年默认为当前年份

cron表达式可以使用在线应用生成:在线Cron表达式生成器 (qqe2.com)

@Component
public class TimedTask {

    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");

    // 每 5 秒执行一次
    @Scheduled(cron = "0/5 * * * * *")
    public void task1() {
        System.out.println("=========执行定时任务1============" +  sdf.format(new Date()));
    }

}
  1. 运行程序,查看结果
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.7.RELEASE)

2022-07-09 23:20:03.523  INFO 21556 --- [           main] c.e.s.ScheduledDemoApplication           : Starting ScheduledDemoApplication on DESKTOP-UT8OKV9 with PID 21556 (E:\Program\Java\ScheduledDemo\target\classes started by Ocean in E:\Program\Java\ScheduledDemo)
2022-07-09 23:20:03.525  INFO 21556 --- [           main] c.e.s.ScheduledDemoApplication           : No active profile set, falling back to default profiles: default
2022-07-09 23:20:03.920  INFO 21556 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'taskScheduler'
2022-07-09 23:20:03.935  INFO 21556 --- [           main] c.e.s.ScheduledDemoApplication           : Started ScheduledDemoApplication in 0.693 seconds (JVM running for 1.442)
=========执行定时任务1============11:20:05
=========执行定时任务1============11:20:10

@Scheduled 注解的属性

❗ @Scheduled 必须使用 cron、fixedDelay、fixedRate之一,三者只能使用一个,否则报错

  1. cron: 声明定时任务的时间规则
  2. zone: 声明 cron 表达式的时区,默认为空字符串,表示本地时区
  3. fixedDelayfixedDelayStringfixedRate,fixedRateString: 指定任务调用的时间间隔,单位毫秒,Spring Boot 启动后就会执行,随后经过指定时间后,再次执行,如此往复。区别是一个是 long 型,一个是 String。
  4. initialDelayinitialDelayString:指定第一次要执行注解注释的方法前,要延迟的毫秒数, 配合fixedDelayfixedDelayStringfixedRate,fixedRateString 使用

fixedDelay 和 fixedRate 示例代码:

@Component
public class TimedTask {

    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");

    @Scheduled(fixedDelay = 5000)
    public void task2() {
        System.out.println("++++++++++执行定时任务2++++++++++" +  sdf.format(new Date()));
    }

    @Scheduled(fixedRate = 5000)
    public void task3() {
        System.out.println("-------------执行定时任务3-------------" +  sdf.format(new Date()));
    }

}

可以看见 Spring Boot 启动后立即执行了定时任务

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.7.RELEASE)

2022-07-09 23:14:35.887  INFO 39512 --- [           main] c.e.s.ScheduledDemoApplication           : Starting ScheduledDemoApplication on DESKTOP-UT8OKV9 with PID 39512 (E:\Program\Java\ScheduledDemo\target\classes started by Ocean in E:\Program\Java\ScheduledDemo)
2022-07-09 23:14:35.889  INFO 39512 --- [           main] c.e.s.ScheduledDemoApplication           : No active profile set, falling back to default profiles: default
2022-07-09 23:14:36.310  INFO 39512 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'taskScheduler'
-------------执行定时任务3-------------11:14:36
++++++++++执行定时任务2++++++++++11:14:36
2022-07-09 23:14:36.325  INFO 39512 --- [           main] c.e.s.ScheduledDemoApplication           : Started ScheduledDemoApplication in 0.661 seconds (JVM running for 1.337)
-------------执行定时任务3-------------11:14:41
++++++++++执行定时任务2++++++++++11:14:41

initialDelay 的使用

@Component
public class TimedTask {

    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
	
    // Spring Boot 启动后,延时 10 秒执行定时任务,每隔 5 秒 执行一次
    @Scheduled(fixedDelay = 5000, initialDelay = 10000)
    public void task2() {
        System.out.println("++++++++++执行定时任务2++++++++++" +  sdf.format(new Date()));
    }

}
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.7.RELEASE)

2022-07-09 23:16:31.763  INFO 18612 --- [           main] c.e.s.ScheduledDemoApplication           : Starting ScheduledDemoApplication on DESKTOP-UT8OKV9 with PID 18612 (E:\Program\Java\ScheduledDemo\target\classes started by Ocean in E:\Program\Java\ScheduledDemo)
2022-07-09 23:16:31.765  INFO 18612 --- [           main] c.e.s.ScheduledDemoApplication           : No active profile set, falling back to default profiles: default
2022-07-09 23:16:32.121  INFO 18612 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'taskScheduler'
2022-07-09 23:16:32.134  INFO 18612 --- [           main] c.e.s.ScheduledDemoApplication           : Started ScheduledDemoApplication in 0.576 seconds (JVM running for 1.37)
++++++++++执行定时任务2++++++++++11:16:42
++++++++++执行定时任务2++++++++++11:16:47
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值