码迷,mamicode.com
首页 > 编程语言 > 详细

Springboot 内置定时器的使用

时间:2019-05-04 09:49:38      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:main   string   out   style   code   多线程   override   over   reg   

定时器又叫定时任务、计划任务,在项目开发中使用比较普遍,它能够定时执行规定的任务,例如:订单到期处理、会员到期处理、数据报表生成等

Springboot内置的定时任务  默认是单线程,使用非常方便,使用时要在Application中设置启用定时任务功能@EnableScheduling,代码如下:

1.启用定时任务功能

@SpringBootApplication
@EnableScheduling
@MapperScan("main.blog.mapper")

public class BootApplication {

    public static void main(String[] args) {
        SpringApplication.run(BootApplication.class, args);
    }
}

2.使用@Scheduled注解执行定时任务

/**
* 每隔5秒执行一次
* @param model 
* @return string
*/
@Scheduled(fixedRate = 5000)
public void testTasks() 
{
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy:mm:dd HH:mm:ss");
    System.out.println("定时任务执行时间:" + dateFormat.format(new Date()));
}

 

3.多线程定时任务的使用

在config下新增配置文件SchedulerConfig.java ,配置自定义线程池,代码如下:

@Configuration
@EnableScheduling  //开启定时器
public class SchedulerConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        //多线程配置
        scheduledTaskRegistrar.setScheduler(taskExecutor());
    }

    @Bean
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(100);
    }
}
然后再用@Scheduled执行任务时,就已经是多线程任务啦。

Springboot 内置定时器的使用

标签:main   string   out   style   code   多线程   override   over   reg   

原文地址:https://www.cnblogs.com/huxiaoguang/p/10807295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!