1 package com.atlassian.sal.core.scheduling;
2
3 import com.atlassian.sal.api.scheduling.PluginJob;
4 import com.atlassian.sal.api.scheduling.PluginScheduler;
5 import org.slf4j.Logger;
6 import org.slf4j.LoggerFactory;
7
8 import java.util.Collections;
9 import java.util.Date;
10 import java.util.HashMap;
11 import java.util.Map;
12 import java.util.Timer;
13 import java.util.TimerTask;
14
15
16
17
18 public class TimerPluginScheduler implements PluginScheduler
19 {
20
21 private final Map<String, Timer> tasks;
22 private final boolean useDaemons;
23
24 public TimerPluginScheduler()
25 {
26 this(Collections.synchronizedMap(new HashMap<String, Timer>()), false);
27 }
28
29 protected TimerPluginScheduler(Map<String, Timer> tasks, boolean useDaemons)
30 {
31 this.tasks = tasks;
32 this.useDaemons = useDaemons;
33 }
34
35 public synchronized void scheduleJob(final String name, final Class<? extends PluginJob> job, final Map<String, Object> jobDataMap, final Date startTime, final long repeatInterval)
36 {
37
38 Timer timer = tasks.get(name);
39 PluginTimerTask task;
40 if (timer != null)
41 {
42 timer.cancel();
43 }
44 timer = new Timer("PluginSchedulerTask-" + name, useDaemons);
45 tasks.put(name, timer);
46 task = new PluginTimerTask();
47 task.setJobClass(job);
48 task.setJobDataMap(jobDataMap);
49 timer.scheduleAtFixedRate(task, startTime, repeatInterval);
50 }
51
52
53
54
55 private static class PluginTimerTask extends TimerTask
56 {
57 private Class<? extends PluginJob> jobClass;
58 private Map<String, Object> jobDataMap;
59 private static final Logger log = LoggerFactory.getLogger(PluginTimerTask.class);
60
61 @Override
62 public void run()
63 {
64 PluginJob job;
65 try
66 {
67 job = jobClass.newInstance();
68 }
69 catch (final InstantiationException ie)
70 {
71 log.error("Error instantiating job", ie);
72 return;
73 }
74 catch (final IllegalAccessException iae)
75 {
76 log.error("Cannot access job class", iae);
77 return;
78 }
79 job.execute(jobDataMap);
80 }
81
82 public Class<? extends PluginJob> getJobClass()
83 {
84 return jobClass;
85 }
86
87 public void setJobClass(final Class<? extends PluginJob> jobClass)
88 {
89 this.jobClass = jobClass;
90 }
91
92 public Map<String, Object> getJobDataMap()
93 {
94 return jobDataMap;
95 }
96
97 public void setJobDataMap(final Map<String, Object> jobDataMap)
98 {
99 this.jobDataMap = jobDataMap;
100 }
101 }
102
103 public void unscheduleJob(final String name)
104 {
105 final Timer timer = tasks.remove(name);
106 if (timer != null)
107 {
108 timer.cancel();
109 }
110 else
111 {
112 throw new IllegalArgumentException("Attempted to unschedule unknown job: " + name);
113 }
114 }
115 }