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