I have a simple application where users can add a post and schedule it to go live at a certain time.
Now I have two approaches before me:
First Approach: I can set a script which will be called every minute and it will check if any posts are pending at the current time and will publish them if they are like so:
My Cron Job:
1 * * * * php myScriptToMakePostLive.php
or
Second Approach I can set cron jobs dynamically on server at the time when user submits his post to publish later. I am using this script:
public function schedulePost(){
$post = new Post();
$post->body = $_POST['body'];
$post->save();
$scheduledTime = Carbon::parse($_POST['publish_on']);
//saving cron dynamically
$output = shell_exec('crontab -l');
file_put_contents('/tmp/crontab.txt', $output.PHP_EOL."{$scheduledTime->minute} {$scheduledTime->hour} {$scheduledTime->day} {$scheduledTime->month} * php myScriptToMakePostLive {$post->id}".PHP_EOL);
echo exec('crontab /tmp/crontab.txt');
die('Your post has been Scheduled !!');
}
What I want to know is which is the better approach and why?
Uh, to be honest, neither.
I'd use a scheduling service like celery. And if I absolutely had to roll my own scheduling service, it'd be with at
and not cron
It also depends on how often you think users will have posts scheduled. I doubt it's all that often.