spring计划任务

本文详细介绍如何在Spring中配置并使用计划任务,包括@Scheduled注解的各种用法,如fixedRate、fixedDelay、initialDelay及cron表达式的解析。通过具体代码示例,展示如何创建定时任务,并提供测试类验证计划任务的正确执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置开启计划任务支持

开启计划任务支持@EnableScheduling

package com.sky.springtest.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@ComponentScan({"com.sky.springtest"})
@EnableScheduling
public class TaskSchedulerConfig {}

计划任务类

spring通过@Scheduled支持多种类型的计划任务

  • fixedRate:固定时间间隔执行
  • fixedDelay:执行完当前任务后,推迟一个时间段再次执行
  • initialDelay:第一次延迟多长时间后再执行
  • cron :
    该参数接收一个cron表达式,cron表达式是一个字符串,字符串以5或6个空格隔开,分开共6或7个域,每一个域代表一个含义。

cron表达式语法
[秒] [分] [小时] [日] [月] [周] [年]
在这里插入图片描述

package com.sky.springtest.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduledTaskService {
	@Scheduled(fixedRate = 5000)
	public void testFixedRate5s() {
		System.err.println("间隔5s执行一次" + System.currentTimeMillis());
	}
	
	@Scheduled(cron = "0 1 12 ? * *")
	public void testFixTimeExecution() {
		System.err.println("每天12点1分:指定时间执行=" + System.currentTimeMillis());
	}
}

测试类

package com.sky.springtest.config;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TaskSchedulerConfigTest {
	private static AnnotationConfigApplicationContext context = null;
	@BeforeClass
	public static void beforeClass() {
		context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);
	}
	@Test
	public void test() {
		// 防止主进程立即运行完毕
		try {
			Thread.sleep(50000);
		} catch (InterruptedException e) {
		}
		context.close();
	}
}
/*测试结果:
间隔5s执行一次1564925649293
间隔5s执行一次1564925654295
间隔5s执行一次1564925659295
延迟10s,间隔5s执行一次1564925659295
间隔5s执行一次1564925664294
延迟10s,间隔5s执行一次1564925664294
间隔5s执行一次1564925669295
延迟10s,间隔5s执行一次1564925669295
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_26264237

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值