SHARE
TWEET

Untitled

a guest Dec 6th, 2019 93 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class Job {
  2.     void run() {
  3.         System.out.println("Running a Job in " + System.currentTimeMillis()/ 1000 + " sec.");
  4.     }
  5. }
  6.  
  7. public class JobRunner {
  8.    
  9.     private class Task {
  10.         Job job;
  11.         long timeToRun;
  12.         public Task(Job job, long timeToRun) {
  13.             this.job = job;
  14.             this.timeToRun = timeToRun;
  15.         }
  16.     }
  17.    
  18.     private PriorityQueue<Task> queue;
  19.     private Thread runnerThread;
  20.    
  21.     public JobRunner() {
  22.         queue = new PriorityQueue<Task>(new Comparator<Task>() {
  23.             public int compare(Task a, Task b) {
  24.                 return (int) Long.compare(a.timeToRun, b.timeToRun);
  25.             }
  26.         });
  27.         runnerThread = new Thread(new Runnable() {
  28.             public void run() {
  29.                 long time = 1000;
  30.                 while (true) {
  31.                     synchronized(queue) {
  32.                         try {
  33.                             queue.wait(time);
  34.                         } catch (InterruptedException e) {}
  35.                        
  36.                         if (queue.isEmpty()) {
  37.                             time = 1000;
  38.                         } else {
  39.                             if (queue.peek().timeToRun <= System.currentTimeMillis() / 1000) {
  40.                                 Task task = queue.poll();
  41.                                 task.job.run();
  42.                                 time = 1; // only wait for 1 millis and return immediately
  43.                             } else {
  44.                                 time = queue.peek().timeToRun * 1000 - System.currentTimeMillis();
  45.                             }
  46.                         }
  47.                     }
  48.                 }
  49.             }
  50.         });
  51.         runnerThread.start();
  52.     }
  53.    
  54.     public void submit(Job job, long delayInSec) {
  55.         synchronized(queue) {
  56.             queue.offer(new Task(job, delayInSec + System.currentTimeMillis() / 1000));
  57.             queue.notify();
  58.         }
  59.     }
  60.    
  61.     public static void main(String[] args) {
  62.         JobRunner runner = new JobRunner();
  63.         Job job1 = new Job();
  64.         Job job2 = new Job();
  65.         Job job3 = new Job();
  66.         runner.submit(job1, 10);
  67.         runner.submit(job2, 1);
  68.         runner.submit(job3, 2);
  69.     }
  70. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top