99网
您的当前位置:首页SpringBoot 实现定时任务

SpringBoot 实现定时任务

来源:99网

定时任务就是企业级开发中最为常见的功能之一,比如定时发送短信,邮件,定时统计各种数量

1. @Scheduled 注解

此注解是由 Spring 提供的定时任务注解,使用方便,配置简单,可以解决工作中大部分要使用到定时任务的场景,使用方式如下:
在启动类上添加 @EnableScheduling 注解开启定时任务,代码如下:

@SpringBootApplication
@EnableScheduling // 启动类添加此注解就表示开启了定时任务功能
public class SoftApplication {
	public static void main(String[] args) {
		SpringApplication.run(SoftApplication.class, args);
	}
}

2. 配置定时任务

定时任务主要通过 @Scheduled 注解进行配置,代码如下:

public class MyScheduled {
	@Scheduled(fixedDelay = 1000)
	public void test1() {
		System.out.println('test1() = ' + new Date());
	}

	@Scheduled(fixedRate = 2000)
	public void test2() {
		System.out.println('test2() = ' + new Date());
	}

	@Scheduled(initialDelay = 1000, fixedRate = 2000)
	public void test3() {
		System.out.println('test3() = ' + new Date());
	}

	@Scheduled(cron = "0 * * * * ?")
	public void test4() {
		System.out.println('test4() = ' + new Date());
	}
}

通过 @Scheduled 注解来标记一个定时任务,其中 fixedDelay = 1000 表示在当前任务执行结束1秒后开启另一个任务,fixedRate = 2000 表示在当前任务开始执行2秒后开启另一个定时任务,initialDelay = 1000 则表示首次执行任务的延迟时间为1秒

@Scheduled 注解中也可以使用 cron 表达式,cron = "0 * * * * ?" 表示此任务每分钟执行一次

因篇幅问题不能全部显示,请点此查看更多更全内容