首先需要一个任务:
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
|
package quartz_project;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** * 一个简单的任务:打印Hello World
*
* @author caijw
*/
public class HelloJob implements Job {
private static Logger _log = LoggerFactory.getLogger(HelloJob. class );
@Override
public void execute(JobExecutionContext ctx) throws JobExecutionException {
//打印Hello World! - 当前日期
_log.info( "Hello World! - " + new Date());
}
} |
由上面代码可以看出,任务类要实现job接口,在execute方法中是任务的具体实现。
然后设定调度策略:
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
package quartz_project;
import java.util.Date;
import org.quartz.DateBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** * 该例子将:
* 1. 展示何如开始和结束quartz的调用器(scheduler),
* 2. 展示在quartz中,调度器是如何运行作业(job)的。
*
* @author caijw
*/
public class SimpleExample {
public void run() throws Exception {
Logger log = LoggerFactory.getLogger(SimpleExample. class );
log.info( "----- Initializing --------" );
//第一步我们必须获取一个调度器
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
log.info( "----- Initialization complete -------" );
//作业的执行时间(这里需要注意,下面详细说明)
Date runTime = DateBuilder.evenMinuteDate( new Date());
log.info( "----- scheduling job --------" );
//创建一项作业
JobDetail job = JobBuilder.newJob(HelloJob. class )
.withIdentity( "job1" , "group1" )
.build();
//创建一个触发器
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity( "trigger1" , "group1" )
.startAt(runTime).build(); //该触发器将在runTime时执行作业
//告诉调度器使用该触发器来安排作业
sched.scheduleJob(job, trigger);
log.info(job.getKey() + " will run at: " + runTime);
sched.start(); //启动调度器
log.info( "------ started scheduler -------" );
log.info( "------ waiting 65 seconds ------" );
try {
Thread.sleep(65L * 1000L);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
log.info( "------- shutting down ------" );
sched.shutdown(); //关闭调度器
log.info( "------- shutdown complete -------" );
}
} |
注意:
1. Date runTime = DateBuilder.evenMinuteDate(new Date()); //当前时间的下一分钟
假如JVM在执行到这一句时,时间为17:23:22,那么runTime就是17:24:00
DateBuilder类似的方法:
2. 并不是把Job的实例注册到Scheduler中,而是JobDetail的实例。
3. Scheduler 实例被关闭之后你就不能调用它的 start() 方法了。这是因为 shutdown() 方法销毁了为 Scheduler 创建的所有的资源(线程,数据库连接等)。假如你在 shutdown() 之后调用 start()你将收到 SchedulerException 的异常。
4. Job 的实例要到该执行它们的时候才会实例化出来。每次 Job 被执行,一个新的 Job 实例会被创建(延迟加载的思想)。所以Job 不必担心线程安全性,因为同一时刻仅有一个线程去执行给定 Job 类的实例,甚至是并发执行同一 Job 也是如此。
Maven的配置文件:
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
< project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
< modelVersion >4.0.0</ modelVersion >
< groupId >quartz_project</ groupId >
< artifactId >quartz_project</ artifactId >
< version >0.0.1-SNAPSHOT</ version >
< packaging >jar</ packaging >
< name >quartz_project</ name >
< url >http://maven.apache.org</ url >
< properties >
< project.build.sourceEncoding >UTF-8</ project.build.sourceEncoding >
</ properties >
< dependencies >
< dependency >
< groupId >org.slf4j</ groupId >
< artifactId >slf4j-log4j12</ artifactId >
< version >1.6.1</ version >
</ dependency >
< dependency >
< groupId >log4j</ groupId >
< artifactId >log4j</ artifactId >
< version >1.2.16</ version >
</ dependency >
< dependency >
< groupId >org.quartz-scheduler</ groupId >
< artifactId >quartz</ artifactId >
< version >2.1.1</ version >
</ dependency >
< dependency >
< groupId >junit</ groupId >
< artifactId >junit</ artifactId >
< version >4.10</ version >
< scope >test</ scope >
</ dependency >
</ dependencies >
</ project >
|
单元测试类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package quartz_project;
import org.junit.Test;
/** * 单元测试
*
* @author caijw
*/
public class SimpleExampleTest {
@Test
public void testRun() throws Exception {
SimpleExample example = new SimpleExample();
example.run();
}
} |
执行结果分析:
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
------------------------------------------------------- T E S T S
------------------------------------------------------- Running quartz_project.SimpleExampleTest [INFO] 25 一月 07:26:16.359 下午 main [quartz_project.SimpleExample] ----- Initializing -------- [INFO] 25 一月 07:26:16.437 下午 main [org.quartz.impl.StdSchedulerFactory] Using default implementation for ThreadExecutor
[INFO] 25 一月 07:26:16.437 下午 main [org.quartz.simpl.SimpleThreadPool] Job execution threads will use class loader of thread: main [INFO] 25 一月 07:26:16.468 下午 main [org.quartz.core.SchedulerSignalerImpl] Initialized Scheduler Signaller of type : class org.quartz.core.SchedulerSignalerImpl
[INFO] 25 一月 07:26:16.468 下午 main [org.quartz.core.QuartzScheduler] Quartz Scheduler v .2.1.1 created.
[INFO] 25 一月 07:26:16.468 下午 main [org.quartz.simpl.RAMJobStore] RAMJobStore initialized. [INFO] 25 一月 07:26:16.468 下午 main [org.quartz.core.QuartzScheduler] Scheduler meta-data: Quartz Scheduler (v2.1.1) 'DefaultQuartzScheduler' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 10 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
[INFO] 25 一月 07:26:16.468 下午 main [org.quartz.impl.StdSchedulerFactory] Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
[INFO] 25 一月 07:26:16.468 下午 main [org.quartz.impl.StdSchedulerFactory] Quartz scheduler version: 2.1.1 [INFO] 25 一月 07:26:16.468 下午 main [quartz_project.SimpleExample] ----- Initialization complete ------- [INFO] 25 一月 07:26:16.484 下午 main [quartz_project.SimpleExample] ----- scheduling job -------- [INFO] 25 一月 07:26:16.500 下午 main [quartz_project.SimpleExample] group1.job1 will run at: Sat Jan 25 19:27:00 CST 2014 [INFO] 25 一月 07:26:16.500 下午 main [org.quartz.core.QuartzScheduler] Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started. [INFO] 25 一月 07:26:16.500 下午 main [quartz_project.SimpleExample] ------ started scheduler ------- [INFO] 25 一月 07:26:16.500 下午 main [quartz_project.SimpleExample] ------ waiting 65 seconds ------ [INFO] 25 一月 07:26:19.703 下午 Timer-0 [org.quartz.utils.UpdateChecker] New Quartz update(s) found: 2.1.7 [http: //www .terracotta.org /kit/reflector ?kitID=default&pageID=QuartzChangeLog]
[INFO] 25 一月 07:27:00.031 下午 DefaultQuartzScheduler_Worker-1 [quartz_project.HelloJob] Hello World! - Sat Jan 25 19:27:00 CST 2014 [INFO] 25 一月 07:27:21.500 下午 main [quartz_project.SimpleExample] ------- shutting down ------ [INFO] 25 一月 07:27:21.500 下午 main [org.quartz.core.QuartzScheduler] Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutting down. [INFO] 25 一月 07:27:21.500 下午 main [org.quartz.core.QuartzScheduler] Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED paused. [INFO] 25 一月 07:27:21.500 下午 main [org.quartz.core.QuartzScheduler] Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutdown complete.
[INFO] 25 一月 07:27:21.500 下午 main [quartz_project.SimpleExample] ------- shutdown complete -------
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 65.39 sec Results : |