Laravel task scheduling without cron jobs for local development

jcs224 profile image Joe Sweeney Updated on ・2 min read

It's very easy to create scheduled tasks in Laravel. They're also pretty easy to run in Linux or MacOS with cron jobs. However, I've been doing a lot of development on Windows lately, and Windows does not have UNIX-style cron jobs. And, there is no mention in Laravel's docs on how to do this properly in Windows. I found this helpful article going over how to do this in Windows using the Task Scheduler, but this felt way too cumbersome. Crawling around arcane Windows settings is not my idea of a good time, and just feels wrong since this is a project-level, not system-level, concern.

So, I found a simple workaround that helps me not only avoid dealing with the Windows Task Scheduler, but also the crontab in macOS and Linux as well! If I were to switch dev computers tomorrow, or bring other people into my project, I have completely cross-platform method of handling scheduled jobs without digging into the guts of my operating system; a NodeJS library.

Using node-schedule

So, I'm not sure if this makes me a bad Laravel dev since I'm not building this tool as an Artisan command (or even in PHP), but it's the most effective and reliable solution available right now without doing a bunch of extra work. Since most Laravel devs are using some sort of front-end tooling (such as Laravel Mix or Webpack), we already have Node (and maybe Yarn) installed on our dev machines, making this less of a burden.

Add node-schedule to your project

Make sure you're cd'd into your Laravel project root and run either the NPM or Yarn command below, depending on what you've got going.

npm install node-schedule --save-dev

# Yarn
yarn add --dev node-schedule

Create JavaScript file for schedule code

Still in your root directory, create a file called dev-scheduler.js, then put the following in that file.

const schedule = require('node-schedule')
const { exec } = require('child_process')

new schedule.scheduleJob('* * * * *', function() {
    exec('php artisan schedule:run', function(error, stdout, stderr) {
        if (error) console.log(error)
        if (stderr) console.log(stderr)

Run the schuduler

Run the new file with Node.

node dev-scheduler.js

And…that's it. Keep in mind this is not for production. Use cron jobs for that.

Enjoy this time-saver!


Editor guide