定时任务@Scheduled入门

一个最简单的例子:
启动类添加注解

@EnableScheduling // 开启定时任务

编写单线程demo

cron 表达式

/**
     * cron 表达式
     * 每2秒执行一次
     * @throws InterruptedException
     */
    @Scheduled(cron = "0/2 * * * * *")
    public void test() throws InterruptedException {
        // 经过测试,使用cron表达式,定时任务第二次会等待第一次执行完毕再开始!
        Thread.sleep(5000L);
        log.info("定时任务测试cron:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

fixedDelay

 /**
     *  fixedDelay:
     *  第一次执行完毕才会执行第二次,时间间隔变为了7秒
     * @throws InterruptedException
     */
    @Scheduled(fixedDelay = 2000L)
    public void test2() throws InterruptedException {
        Thread.sleep(5000L);
        log.info("定时任务测试fixedDelay:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

fixedRate

 /**
     *  fixedRate:
     *  每隔2秒就会执行, 但是因为单线程,所以在5秒后会输出,间隔就是5秒
     * @throws InterruptedException
     */
    @Scheduled(fixedRate = 2000L)
    public void test3() throws InterruptedException {
        Thread.sleep(5000L);
        log.info("定时任务测试fixedRate:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }


如果是一起执行这三个定时任务,那么会一个一个的来, 因为只有一个线程.

多线程

/**
 *
 * @author GMaya
 */
@Configuration
@EnableAsync
public class ScheduleConfig {
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(50); // 设置线程池大小
        return taskScheduler;
    }
}

如果只是加这一个配置类, 确实是使用了多线程, 每个定时任务都互相不影响.
但是一个线程第一次阻塞了,第二次就不行了,所以在定时任务上再加

@Async


就是说你这次失败了, 不要影响我下次的运行

发布了70 篇原创文章 · 获赞 30 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/gfl1427097103/article/details/105195576
今日推荐