SpringBoot中使用定时器

1、相关知识

一个不错的各种环境类型下的Cron表达式生成

在线Cron表达式生成器

@Scheduled注解各参数详解

2、注解使用

@EnableScheduling:定时任务开关。
@EnableAsync:方法按周期新启动一个线程异步开关。
@Scheduled(cron = "0/5 * * * * ?"):配置定时任务。
@Async:方法按周期新启动一个线程。

3、使用示例

配置类:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@Configuration
@EnableScheduling
@EnableAsync
public class ScheduleConfig {
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(50);
        return taskScheduler;
    }
}

具体定时任务类:

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

import java.text.SimpleDateFormat;
import java.util.Date;
	
@Component
public class SchedulDemo {

    //@Async
    @Scheduled(cron = "0/5 * * * * ?")
    public void Test(){
        try {
            long threadId = Thread.currentThread().getId();

            System.out.println("1-start-1,tid="+threadId+","+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

            Thread.sleep(12*1000);

            System.out.println("1-end-1,tid="+threadId+","+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        }
        catch (Exception ex){
            System.out.println(ex.getMessage());
        }
    }

    @Async
    @Scheduled(cron = "0/5 * * * * ?")
    public void Test2(){
        try {
            long threadId = Thread.currentThread().getId();

            System.out.println("1-start-2,tid="+threadId+","+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

            Thread.sleep(12*1000);

            System.out.println("1-end-2,tid="+threadId+","+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        }
        catch (Exception ex){
            System.out.println(ex.getMessage());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值