Search code examples
phplaravellaravel-scheduler

How to subtract days from Laravel command scheduler?


I need to run a command that creates database table each year quarter, and I found this command

$schedule->command('test:create-table table_test')->quarterly();

But I want to run this command a week before, just to be sure that the table already created before I start insert data into it.

What is the best way to achieve that?


Solution

  • Under the hood, Laravel implements "quarterly" as the first day of every quarter at 00:00 with the cron statement 0 0 1 1-12/3 *

    While there isn't a built-in "weekBefore" method, there is a cron() method, and you can get fairly close by picking, for example, the 24th day of particular months in a single cron statement. Eg:

    // Run on the 24th of Mar, Jun, Sept, and Dec
    $schedule->command('foo')->cron('0 0 24 3,6,9,12 *');
    

    If you wanted to be exactly the week before, you'd have to break it up into at least two statements (because Mar & Dec have 31 days, while Jun & Sep have 30).