Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Job {
- void run() {
- System.out.println("Running a Job in " + System.currentTimeMillis()/ 1000 + " sec.");
- }
- }
- public class JobRunner {
- private class Task {
- Job job;
- long timeToRun;
- public Task(Job job, long timeToRun) {
- this.job = job;
- this.timeToRun = timeToRun;
- }
- }
- private PriorityQueue<Task> queue;
- private Thread runnerThread;
- public JobRunner() {
- queue = new PriorityQueue<Task>(new Comparator<Task>() {
- public int compare(Task a, Task b) {
- return (int) Long.compare(a.timeToRun, b.timeToRun);
- }
- });
- runnerThread = new Thread(new Runnable() {
- public void run() {
- long time = 1000;
- while (true) {
- synchronized(queue) {
- try {
- queue.wait(time);
- } catch (InterruptedException e) {}
- if (queue.isEmpty()) {
- time = 1000;
- } else {
- if (queue.peek().timeToRun <= System.currentTimeMillis() / 1000) {
- Task task = queue.poll();
- task.job.run();
- time = 1; // only wait for 1 millis and return immediately
- } else {
- time = queue.peek().timeToRun * 1000 - System.currentTimeMillis();
- }
- }
- }
- }
- }
- });
- runnerThread.start();
- }
- public void submit(Job job, long delayInSec) {
- synchronized(queue) {
- queue.offer(new Task(job, delayInSec + System.currentTimeMillis() / 1000));
- queue.notify();
- }
- }
- public static void main(String[] args) {
- JobRunner runner = new JobRunner();
- Job job1 = new Job();
- Job job2 = new Job();
- Job job3 = new Job();
- runner.submit(job1, 10);
- runner.submit(job2, 1);
- runner.submit(job3, 2);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement