This is a problem from Daily Coding Problem. I have implemented it in Java.
For a function f
I have used Runnable
interface.
Problem:
This problem was asked by Apple.
Implement a job scheduler which takes in a function f
and an integer n
, and calls f
after n
milliseconds.
Solution:
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
class Ideone {
interface JobScheduler {
void schedule(final Runnable f, int n);
}
static class JobSchedulerImpl implements JobScheduler {
private final AtomicInteger idValue = new AtomicInteger(0);
private final Map<Integer, Thread> jobs = new ConcurrentHashMap<>();
private int getNextId() {
return idValue.incrementAndGet();
}
@Override
public void schedule(final Runnable f, final int n) throws IllegalArgumentException {
if (n < 0) {
throw new IllegalArgumentException("n cannot be nagative");
}
int id = getNextId();
Thread job = new Thread() {
@Override
public void run() {
try {
Thread.sleep(n);
f.run();
jobs.remove(id);
} catch (InterruptedException e) {
jobs.remove(id);
}
}
};
jobs.put(id, job);
job.start();
}
}
public static void main(String[] args) {
JobScheduler jobScheduler = new JobSchedulerImpl();
jobScheduler.schedule(new Runnable() {
@Override
public void run() {
System.out.println("Job1 launched at: " + System.currentTimeMillis());
}
}, 10000);
jobScheduler.schedule(new Runnable() {
@Override
public void run() {
System.out.println("Job2 launched at: " + System.currentTimeMillis());
}
}, 1000);
}
}
```