SpringBoot2注解配置定时任务和异步执行任务

springboot集成schedule

背景


 在项目开发过程中,我们经常需要执行具有周期性的任务。通过定时任务可以很好的帮助我们实现。

我们拿常用的几种定时任务框架做一个比较:

从以上表格可以看出,Spring Schedule框架功能完善,简单易用。对于中小型项目需求,Spring Schedule是完全可以胜任的。

1、springboot2集成schedule


1.1 添加maven依赖包

由于Spring Schedule包含在spring-boot-starter基础模块中了,所有不需要增加额外的依赖。

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

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

1.2 启动类,添加启动注解

在springboot入口或者配置类中增加@EnableScheduling注解即可启用定时任务。

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

1.3.添加定时任务  

我们将对Spring Schedule三种任务调度器分别举例说明。

1.3.1 Cron表达式

类似于Linux下的Cron表达式时间定义规则。Cron表达式由6或7个空格分隔的时间字段组成,如下图:

常用cron表达式:

"0 0 10,14,16 * * ?" 每天上午10点,下午2点,4点 
"0 0/30 9-17 * * ?" 朝九晚五工作时间内每30分钟
"0 0/30 9-17 ? * 1-5" 周一至周五工作日内,每天朝九晚五工作时间内每30分钟 
"0 0 12 ? * WED" 表示每个星期三中午12点 
"0 0 12 * * ?" 每天中午12点触发 
"0 15 10 ? * *" 每天上午10:15触发 
"0 15 10 * * ?" 每天上午10:15触发 
"0 15 10 * * ? *" 每天上午10:15触发 
"0 15 10 * * ? 2005" 2005年的每天上午10:15触发 
"0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发 
"0 0/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发 
"0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发 
"0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发 
"0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发 
"0 15 10 ? * MON-FRI" 周一至周五的上午10:15触发 
"0 15 10 15 * ?" 每月15日上午10:15触发 
"0 15 10 L * ?" 每月最后一日的上午10:15触发 
"0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发 
"0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一个星期五上午10:15触发 
"0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发

举个栗子:

添加一个work()方法,每10秒执行一次。

注意:当方法的执行时间超过任务调度频率时,调度器会在下个周期执行。

如:假设work()方法在第0秒开始执行,方法执行了12秒,那么下一次执行work()方法的时间是第20秒。

@Component
public class MyTask {
    @Scheduled(cron = "0/10 * * * * *")
    public void work() {
        // task execution logic
    }
}

1.3.2 固定间隔任务

 下一次的任务执行时间,是从方法最后一次任务执行结束时间开始计算。并以此规则开始周期性的执行任务。

举个栗子:

添加一个work()方法,每隔10秒执行一次。

例如:假设work()方法在第0秒开始执行,方法执行了12秒,那么下一次执行work()方法的时间是第22秒。

@Scheduled(fixedDelay = 1000*10)
public void work() {
    // task execution logic
}

1.3.3 固定频率任务  

 按照指定频率执行任务,并以此规则开始周期性的执行调度。

举个栗子:

添加一个work()方法,每10秒执行一次。

注意:当方法的执行时间超过任务调度频率时,调度器会在当前方法执行完成后立即执行下次任务。

例如:假设work()方法在第0秒开始执行,方法执行了12秒,那么下一次执行work()方法的时间是第12秒。

@Scheduled(fixedRate = 1000*10)
public void work() {
    // task execution logic
}

2、配置TaskScheduler线程池


 在实际项目中,我们一个系统可能会定义多个定时任务。那么多个定时任务之间是可以相互独立且可以并行执行的。

通过查看org.springframework.scheduling.config.ScheduledTaskRegistrar源代码,发现spring默认会创建一个单线程池。这样对于我们的多任务调度可能会是致命的,当多个任务并发(或需要在同一时间)执行时,任务调度器就会出现时间漂移,任务执行时间将不确定。

protected void scheduleTasks() {
    if (this.taskScheduler == null) {
        this.localExecutor = Executors.newSingleThreadScheduledExecutor();
        this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
    }
    //省略...
}

2.1 自定义线程池  

新增一个配置类,实现SchedulingConfigurer接口。重写configureTasks方法,通过taskRegistrar设置自定义线程池。

@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }   
    @Bean(destroyMethod="shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(20);
    }
}

3、实际应用中的问题


 3.1 Web应用中的启动和关闭问题

我们知道通过spring加载或初始化的Bean,在服务停止的时候,spring会自动卸载(销毁)。但是由于线程是JVM级别的,如果用户在Web应用中启动了一个线程,那么这个线程的生命周期并不会和Web应用保持一致。也就是说,即使Web应用停止了,这个线程依然没有结束(死亡)。

解决方法:

1)当前对象是通过spring初始化

spring在卸载(销毁)实例时,会调用实例的destroy方法。通过实现DisposableBean接口覆盖destroy方法实现。在destroy方法中主动关闭线程。

@Component
public class MyTask implements DisposableBean{
    @Override
    public void destroy() throws Exception {
        //关闭线程或线程池
        ThreadPoolTaskScheduler scheduler = (ThreadPoolTaskScheduler)applicationContext.getBean("scheduler");
        scheduler.shutdown();
    }
    //省略...
}

2)当前对象不是通过spring初始化(管理) 

那么我们可以增加一个Servlet上下文监听器,在Servlet服务停止的时候主动关闭线程。

public class MyTaskListenter implements ServletContextListener{
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        //关闭线程或线程池
    }
    //省略...
}

3.2 分布式部署问题

在实际项目中,我们的系统通常会做集群、分布式或灾备部署。那么定时任务就可能出现并发问题,即同一个任务在多个服务器上同时在运行。

解决方法(分布式锁):

1)通过数据库表锁

2)通过缓存中间件

3)通过Zookeeper实现

4、异步任务@EnableAsync

1、启动类加注解@EnableAsync开启异步任务,自动扫描:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync //开启异步
public class Application {
 
    public static void main(String[] args) {
        final SpringApplication application = new SpringApplication(com.xxx.xxx.Application.class);
        application.run(args);
    }
}

2、定义异步任务并使用@Component标记组件被容器扫描,异步方法加上@Async

注意:

1)要把异步任务封装到类里面,不能直接写到Controller;

2)增加Future<String>返回结果AsyncResult<String>("task执行完成")

3)如果需要拿到结果,需要判断全部的task.isDone();

4)通过注入方式,注入到Controller里面,如果改为同步任务需要把@Async注释掉;

4)异步任务无返回结果。

异步任务业务类:

// 异步任务业务类
@Component
@Async
public class AsyncTask {
 
	public Future<String> task1() throws InterruptedException {
		long begin = System.currentTimeMillis();
		TimeUnit.SECONDS.sleep(1);
		long end = System.currentTimeMillis();
		System.out.println("任务1耗时=" + (end - begin));
		return new AsyncResult<String>("任务1");
	}
 
	public Future<String> task2() throws InterruptedException {
		long begin = System.currentTimeMillis();
		TimeUnit.SECONDS.sleep(2);
		long end = System.currentTimeMillis();
		System.out.println("任务2耗时=" + (end - begin));
		return new AsyncResult<String>("任务2");
	}
 
	public Future<String> task3() throws InterruptedException {
		long begin = System.currentTimeMillis();
		TimeUnit.SECONDS.sleep(3);
		long end = System.currentTimeMillis();
		System.out.println("任务3耗时=" + (end - begin));
		return new AsyncResult<String>("任务3");
	}
 
}

测试类:


@RestController
@RequestMapping("/api/v1")
public class UserController {
	@Autowired
	private AsyncTask asyncTask;
 
	@RequestMapping("async_task")
	public String exeTask() throws InterruptedException {
		long begin = System.currentTimeMillis();
		Future<String> task1 = asyncTask.task1();
		Future<String> task2 = asyncTask.task2();
		Future<String> task3 = asyncTask.task3();
		for (;;) {
			if (task1.isDone() && task2.isDone() && task3.isDone()) {
				break;
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("执行总耗时=" + (end - begin));
		return "success";
	}
}
发布了248 篇原创文章 · 获赞 32 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/tianshan2010/article/details/104046257