Spring中的定时任务
来源:互联网 发布:ubuntu如何卸载samba 编辑:程序博客网 时间:2024/06/05 03:14
以前在web应用中定时任务都是用的quartz,但Spring在3.0版本之后添加了Spring Task。
具体的配置如下:
<task:scheduled-tasks scheduler="taskScheduler"> <!--<task:scheduled ref="taskManager" method="print" cron="1/5 * * * * *"/>--> <task:scheduled ref="taskManager" method="print" fixed-rate="10000"/> </task:scheduled-tasks> <bean id="taskScheduler" class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler" p:poolSize="1" p:errorHandler-ref="errorHandler" p:waitForTasksToCompleteOnShutdown="true"/> <bean id="errorHandler" class="org.xyz.test.service.task.TaskManager.TestExceptionHandler"/>
上面的代码是Spring的配置文件中的一部分内容,首先定义了一个任务调度器,该任务调度器不但拥有定时调度的功能,同时里面还包含一个线程池。我们来看下ThreadPoolTaskScheduler的源码:
public class ThreadPoolTaskScheduler extends ExecutorConfigurationSupportimplements TaskScheduler, SchedulingTaskExecutor {private volatile int poolSize = 1;private volatile ScheduledExecutorService scheduledExecutor;private volatile ErrorHandler errorHandler;//省略下面的内容}
可见该任务调度器里面是一个ScheduledExecutorService,该类是ExecutorService类的子类。关于ExecutorService类,这是java.util.concurrent包中的很重要的类,详细参见笔者以前的博客 JAVA并发-Executor任务执行框架。
看了ScheduledExecutorService类的源码,那他的用法就很清晰了,首先需要指定其中的线程池的线程数数量,然后指定其他的,比如很重要的一个,如果发生异常的话怎么办?上面的配置中是为异常指定了一个异常处理类。我们来看具体的代码:
/** * Created by yizhenn on 16-12-17. */@Servicepublic class TaskManager { public void print() throws TestException, InterruptedException { Random random = new Random(System.currentTimeMillis()); int tmp = random.nextInt(5); System.out.println("random second=" + tmp); if (tmp == 1) throw new TestException(); TimeUnit.SECONDS.sleep(tmp); System.out.println("执行定时任务"); } public static class TestExceptionHandler implements ErrorHandler { @Override public void handleError(Throwable t) { System.out.println("定时任务发生异常,进行处理"); } } private class TestException extends Exception { }}
好了,看来使用spring task的定时任务框架还是挺简单的。关于ThreadPoolTaskScheduler这个类的属性,都是一些java.util.concurrent.*包中的类,可参见笔者的博客集Java并发
觉得文章不错的话,就关注我吧!
具体工程代码,请见我的github!
https://github.com/ZhenShiErGe/test/pull/3/commits
0 0
- spring中的定时任务
- spring中的定时任务
- spring中的定时任务
- Spring中的定时任务
- spring中的定时任务-@scheduled
- 关于spring中的定时任务
- 初探Spring中的定时任务
- Spring中的时间调度,定时任务
- Spring中的时间调度,定时任务
- Spring中的时间调度,定时任务
- Spring中的时间调度,定时任务
- Spring计划任务(定时任务)
- Spring 定时任务功能
- Spring 定时任务实现
- spring执行定时任务
- spring执行定时任务
- spring多定时任务
- Spring+Quartz定时任务
- Markdown语法
- vbs(Visual Basic Script) 笔记
- android 编译
- [转帖]易飞9.0.9注册机
- 闲谈System.nanoTime()函数
- Spring中的定时任务
- 学好Python的优秀资源推荐
- 【数据结构】数据结构C语言的实现【图(邻接表法)】
- Spring入门
- 【leetcode】63. Unique Paths II【java】
- 将Excel表格中的数据导出到xml文件中
- 互联网公司产品经理们面试的终极攻略
- 【leetcode】64. Minimum Path Sum【java】
- 第十二章—PopupWindow