【WEEK15】 【DAY3】Scheduled Tasks【English Version】

2024.6.5 Wednesday
Following 【WEEK15】 【DAY2】【DAY3】Email Tasks【English Version】

17. Asynchronous, Scheduled, and Email Tasks

17.3. Scheduled Tasks

In project development, it is often necessary to execute some scheduled tasks, such as analyzing the previous day’s log information at midnight every day. Spring provides us with asynchronous task scheduling methods, offering two interfaces (see TaskExecutor.class and TaskScheduler.class for details).

  • TaskExecutor interface (Task Executor)
  • TaskScheduler interface (Task Scheduler)

17.3.1. Two Annotations:

  • @EnableScheduling——Annotation to enable scheduling
  • @Scheduled——When to execute

17.3.2. Cron Expression

Cron Expression:

FieldAllowed ValuesAllowed Special Characters
Second0-59, - * /
Minute0-59, - * /
Hour0-23, - * /
Day1-31, - * / ? L W C
Month1-12, - * /
Week0-1 or SUN-SAT 0,7 is SUN, - * / ? L W C
Special CharacterMeaning
,Enumeration
-Range
*Any
/Step
?Day/Week conflict match
LLast
WWeekday
CValue calculated after calendar practice
#Week, 4#2 means the second Wednesday of the month

17.3.3. Modify Springboot09TestApplication.java to Enable Scheduling

package com.P51;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableAsync   // Enable asynchronous annotation functionality

@EnableScheduling  // Enable scheduling annotation functionality

@SpringBootApplication
public class Springboot09TestApplication {

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

}

17.3.4. Create ScheduledService.java

package com.P51.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledService {
    // Cron expression (you can search for explanations online)
    @Scheduled(cron = "30 06 14 * * ?") // Execute once daily at 14:06:30
    @Scheduled(cron = "0/2 * * * * ?")  // Execute every two seconds daily
    public void hello(){
        System.out.println("execute");
    }
}

Official explanation, very detailed and worth reading:
Insert image description here
Insert image description here

Other references:
https://www.bejson.com/othertools/cron/
Insert image description here

17.3.5. Restart the Project

Insert image description here

Insert image description here

  • 68
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值