原生的Java定时器
使用Java.util包下的定时器也很简单,具体代码如下:
1
2
3
4
5
6
7
8
9
10
11
|
//设置定时器开始时间
Date time = sdf.parse( "2020-10-01 16:40:00" );
//设置定时器
Timer timer = new Timer();
//第三个参数表示每隔多久循环一次
timer.schedule( new TimerTask() {
@Override
public void run() {
System.out.println( "嗨" );
}
}, time, 3000 );
|
Spring的定时器
- 1)导包,除了spring提供的包之外,还需要quartz包(可以到maven仓库中去下载)
- 2)自定义Task类:
当定时器启动时,Spring执行我们指定Task中的方法
- 3)MethodInvokingJobDetailFactoryBean类:
将自定义的Task类交给MethodInvokingJobDetailFactoryBean,并告诉它Task的执行方法,由它负责去执行
- 4)CronTriggerFactoryBean触发器:
定义定时器触发的时间,以及执行对象
- 5)SchedulerFactoryBean:
将触发器对象交给它统一保管
配置信息如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<? xml version = "1.0" encoding = "UTF-8" ?>
< beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd ">
<!-- 定时器-->
< bean id = "myTask" class = "com.cjh.MyTask" ></ bean >
<!-- 创建一个Spring提供好的计时器对象,用来做倒计时管控-->
< bean id = "taskExecutor" class = "org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" >
< property name = "targetObject" ref = "myTask" />
< property name = "targetMethod" value = "test" />
</ bean >
<!-- 触发器-->
< bean id = "cronTrigger" class = "org.springframework.scheduling.quartz.CronTriggerFactoryBean" >
< property name = "jobDetail" ref = "taskExecutor" />
< property name = "cronExpression" value = "30/5 41 18 * * ?" />
</ bean >
<!-- 管理触发器对象的容器-->
< bean class = "org.springframework.scheduling.quartz.SchedulerFactoryBean" >
< property name = "triggers" >
< list >
< ref bean = "cronTrigger" />
</ list >
</ property >
</ bean >
</ beans >
|
- 6)主函数
只需要加载配置文件,触发器就会启动
1
2
3
4
5
|
public class TestMain {
public static void main(String[] args) throws MessagingException, ParseException {
ApplicationContext context = new ClassPathXmlApplicationContext( "ApplicationContext.xml" );
}
}
|
以上就是浅析spring定时器的使用的详细内容,更多关于spring 定时器的资料请关注服务器之家其它相关文章!
原文链接:https://segmentfault.com/a/1190000025185454?utm_source=tuicool&utm_medium=referral