Problem
Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.
Solution
Implementing a job scheduler that invokes a function f
after n
milliseconds can be achieved using threading and timers
Code
Java
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class JobScheduler {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void jobScheduler(Runnable f, int n) {
scheduler.schedule(f, n, TimeUnit.MILLISECONDS);
}
public static void main(String[] args) {
JobScheduler js = new JobScheduler();
Runnable exampleFunction = new Runnable() {
@Override
public void run() {
System.out.println("Function called!");
}
};
// Call exampleFunction after 2000 milliseconds (2 seconds)
js.jobScheduler(exampleFunction, 2000);
}
}
Python
import threading
def job_scheduler(f, n):
# Start a timer that runs the function f after n milliseconds
timer = threading.Timer(n / 1000.0, f) # n milliseconds is n/1000 seconds
timer.start()
# Example usage
def example_function():
print("Function called!")
# Call example_function after 2000 milliseconds (2 seconds)
job_scheduler(example_function, 2000)