SpringBoot 【定时篇】

1. 启动类添加注解@EnableScheduling

@SpringBootApplication
@EnableScheduling
public class App 
{
    public static void main( String[] args )
    {
    	SpringApplication.run(App.class, args);
    }
}

2. 在pom.xml里添加定时依赖包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
 </dependency>

3. 添加定时任务

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

@Component
public class ScheduledTask {
    
	 	//定时器1.
		//@Scheduled(fixedRate = 1000*60*60)
	    @Scheduled(fixedDelay = 100)
	    public void task1(){
	        for (int i = 0; i < 5; i++) {
	        	System.out.println("task1======" + Thread.currentThread().getName() + ", " + i);
	        }
	    }
	 
	    //定时器2.
	    @Scheduled(fixedDelay = 100)
	    //@Scheduled(cron="*/2 * * * * ? ")
	    public void task2(){
	        for (int i = 0; i < 5; i++) {
	        	System.out.println("task2====" + Thread.currentThread().getName() + ", " + i);
	        }
	    }
}

给类添加@Component,定时任务添加@Scheduled。
定时周期控制可以参考 https://juejin.im/post/5b90dd46f265da0a8c6c02f7

4. 定时任务并发控制
如果需要启动多个定时任务,系统默认是在一个线程里顺序执行,达不到并发高效,可以配置定时多线程(只需一个,多个也只有一个有用)。如下:

@Configuration
public class ScheduleConfig  implements SchedulingConfigurer{
	@Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值