Interview Questions — Crafting a Simple Job Scheduler

Umur Alpay
CodeResult
Published in
2 min readApr 4, 2024
Photo by Icons8 Team on Unsplash

Implement a job scheduler that takes in a function f and an integer n and calls f after n milliseconds. We will solve this question in both JS and PHP.

Javascript Solution

Implementing a job scheduler in JavaScript is not only logical but also straightforward due to JavaScript’s built-in support for scheduling tasks with functions like setTimeout(). The setTimeout() function allows you to execute a function once after a specified period of time, which is measured in milliseconds. This fits perfectly with the requirement of the interview question to call a function f after n milliseconds.

function jobScheduler(f, n) {
setTimeout(f, n);
}

// Example usage
jobScheduler(() => console.log("Hello, world!"), 2000); // Calls the function after 2000 milliseconds

PHP Solution

In PHP, scheduling a function call to occur after a delay is not as straightforward as in JavaScript because PHP is primarily a synchronous server-side language. However, you can simulate a delay before executing a function using the sleep() function for delays in seconds or usleep() for delays in microseconds. Keep in mind that these functions block the execution of the script, which means the script will wait for the specified time before continuing execution. This behavior is quite different from JavaScript's setTimeout(), which is non-blocking.

To call a function after n milliseconds in PHP, you can use usleep(), where 1 second equals 1,000,000 microseconds. Here's how you might implement a simple job scheduler in PHP:

function jobScheduler($f, $n) {
usleep($n * 1000); // Convert milliseconds to microseconds
call_user_func($f); // Call the function
}
// Example usage
jobScheduler(function() {
echo "Hello, world!";
}, 2000); // Calls the function after 2000 milliseconds (2 seconds)

Follow me on Instagram, Facebook or Twitter if you like to keep posted about tutorials, tips and experiences from my side.

You can support me from Patreon, Github Sponsors, Ko-fi or Buy me a coffee

--

--