1 package com.atlassian.sal.core.scheduling;
2
3 import com.atlassian.sal.api.scheduling.PluginJob;
4 import com.google.common.base.Predicate;
5 import junit.framework.TestCase;
6
7 import java.util.Collections;
8 import java.util.Date;
9 import java.util.Map;
10 import java.util.concurrent.Executors;
11 import java.util.concurrent.ScheduledExecutorService;
12 import java.util.concurrent.atomic.AtomicInteger;
13
14 public class ExecutorPluginSchedulerTest extends TestCase {
15
16 private ScheduledExecutorService executor;
17 private ExecutorPluginScheduler scheduler;
18
19 protected void setUp() throws Exception {
20 executor = Executors.newScheduledThreadPool(1);
21 scheduler = new ExecutorPluginScheduler(executor);
22 }
23
24 @Override
25 public void tearDown() throws Exception {
26 executor.shutdown();
27 }
28
29 public void testSchedule() throws Exception {
30 scheduler.scheduleJob("test1", TestPluginJob.class, Collections.<String, Object>emptyMap(), new Date(), 60000);
31 waitForCondition(new Predicate<AtomicInteger>() {
32 @Override
33 public boolean apply(AtomicInteger input) {
34 return input.get() == 1;
35 }
36 }, 180000);
37 scheduler.unscheduleJob("test1");
38 assertJobIsNotScheduled("test1");
39
40 scheduler.scheduleJob("test2", TestPluginJob.class, Collections.<String, Object>emptyMap(), new Date(), 500);
41 waitForCondition(new Predicate<AtomicInteger>() {
42 @Override
43 public boolean apply(AtomicInteger input) {
44 return input.get() > 1;
45 }
46 }, 180000);
47 scheduler.unscheduleJob("test2");
48 assertJobIsNotScheduled("test2");
49 }
50
51 public void testUnscheduleInexisting() throws Exception {
52 assertJobIsNotScheduled("inexistingjob");
53 }
54
55 private void waitForCondition(Predicate<AtomicInteger> condition, int timeoutInMs) throws InterruptedException {
56 long start = System.currentTimeMillis();
57 while (!condition.apply(TestPluginJob.executionCount) && (System.currentTimeMillis() - start < timeoutInMs)) {
58 Thread.sleep(500);
59 }
60 }
61
62 private void assertJobIsNotScheduled(String jobKey) {
63 try {
64 scheduler.unscheduleJob(jobKey);
65 fail("IllegalArgumentException should have thrown");
66 } catch (IllegalArgumentException e) {
67 assertTrue(e.getMessage().contains("unknown job"));
68 }
69 }
70
71 public static class TestPluginJob implements PluginJob {
72 private static final AtomicInteger executionCount = new AtomicInteger(0);
73
74 @Override
75 public void execute(Map<String, Object> jobDataMap) {
76 executionCount.incrementAndGet();
77 }
78 }
79 }