Spring定时任务(附带:Cron表达式从配置文件读取)

Spring定时任务

定时任务的注解主要有3个:

// 1.主要用于标记配置类,兼备Component的效果。
@Configuration

// 2.开启定时任务。
@EnableScheduling

// 3. 放在作为定时任务的方法上,标识为定时任务。
@Scheduled

代码示例

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration // 1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class TestJob {
    
    

	Log log = LogFactory.getLog(getClass());

	// 容器启动后,延迟60秒后再执行一次定时器,以后每60秒再执行一次该定时器。
	@Scheduled(initialDelay = 60 * 1000, fixedRate = 60 * 1000)
	public void doWork() {
    
    
		log.info("定时任务:执行");
	}
}

设置定时任务的两种方式

代码中直接设置(硬编码,不推荐)

如上述代码中,使用 initialDelay 和 fixedRate ,直接设置时间。

从配置文件中读取 Cron 表达式(推荐)

定时任务代码

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration // 1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class TestJob {
    
    

	Log log = LogFactory.getLog(getClass());

	// 定时器触发时间的cron,从配置文件 properties/yaml 中读取。
	@Scheduled(cron = "${test.job.cron}")
	public void doWork() {
    
    
		log.info("定时任务:执行");
	}
}

对应的 application.properties 配置:

# TestJob定时任务的cron表达式:每隔1分钟执行一次。
test.job.cron=0 * * * * *

Cron表达式

每隔1分钟执行一次(整分钟)

test.job.cron=0 * * * * *

在这里插入图片描述

每隔5分钟执行一次(整分钟)

0 */5 * * * *

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/sgx1825192/article/details/131852764
今日推荐