侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 747 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

SpringBoot(34)之定时任务简单使用

zze
zze
2018-08-27 / 0 评论 / 0 点赞 / 374 阅读 / 2624 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

1、使用 Maven 创建 SpringBoot 项目,引入 Web 场景启动器。

2、编写定时任务类,使用 Cron 表达式指定任务执行时机,注册到 IoC 容器:

// zze.springboot.task.service.ScheduleService
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class ScheduleService {
    @Scheduled(cron = "*/3 * * * * ?")  // 编写 cron 表达式,每 3 秒执行一次
    public void test(){
        Date now = new Date();
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
        System.out.println(timeFormat.format(now));
    }
}

3、使用注解开启定时任务支持:

// zze.springboot.task.TaskApplication
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling // 开启定时任务支持
@SpringBootApplication
public class TaskApplication {

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

}

4、启动项目测试:

hello at 21:32:57
hello at 21:33:00
hello at 21:33:03
hello at 21:33:06
/*
每间隔 3 秒控制台会执行 hello 方法
*/

SpringBoot 中的定时任务 Cron 表达式与任务调度框架 Quartz 的 Cron 表达式规则相似,可参考【Cron 表达式】。

但它们有一处区别是:

  • SpringBoot 任务的 Cron 表达式中星期部分 1-6 为周一到周六,0 和 7 都为周日。
  • Quartz 框架的 Cron 表达式中星期部分 1-7 为周日到周六。

上述创建的任务默认是串行执行,如果需要使用多线程来创建并行任务,可添加如下配置类来配置线程池:

@Configuration
@EnableScheduling
public class AsyncTaskConfig implements SchedulingConfigurer, AsyncConfigurer {
	//线程池线程数量
	private int corePoolSize = 5;

	@Bean
	public ThreadPoolTaskScheduler taskScheduler()
	{
		ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
		scheduler.initialize();//初始化线程池
		scheduler.setPoolSize(corePoolSize);//线程池容量
		return scheduler;
	} 

	@Override
	public Executor getAsyncExecutor() {
		Executor executor = taskScheduler();
		return executor;
	} 

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return null;
	} 

	@Override
	public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
		scheduledTaskRegistrar.setTaskScheduler(taskScheduler());
	}
}

@EnableScheduling 添加到此配置类上,SpringBoot 启动类上不用再添加 @EnableScheduling

0

评论区