diff --git a/web/app/Models/CronJob.php b/web/app/Models/CronJob.php index eff27036..a0a581e1 100644 --- a/web/app/Models/CronJob.php +++ b/web/app/Models/CronJob.php @@ -17,50 +17,70 @@ public static function boot() { parent::boot(); - static::created(function ($model) { - $model->configureCronJobs(); + static::creating(function ($model) { + $allCronJobs = []; + $oldCronJobs = self::where('user', $model->user)->get(); + foreach ($oldCronJobs as $oldCronJob) { + $allCronJobs[$oldCronJob->user][] = $oldCronJob->toArray(); + } + $allCronJobs[$model->user][] = $model->toArray(); + + $model->configureCronJobs($allCronJobs); }); - static::updated(function ($model) { - $model->configureCronJobs(); + static::updating(function ($model) { + $allCronJobs = []; + $oldCronJobs = self::where('user', $model->user)->get(); + foreach ($oldCronJobs as $oldCronJob) { + if ($oldCronJob->id == $model->id) { + $allCronJobs[$model->user][] = $model->toArray(); + continue; + } + $allCronJobs[$oldCronJob->user][] = $oldCronJob->toArray(); + } + $model->configureCronJobs($allCronJobs); }); - static::deleted(function ($model) { - $model->configureCronJobs(); + static::deleting(function ($model) { + $allCronJobs = []; + $oldCronJobs = self::where('user', $model->user)->get(); + foreach ($oldCronJobs as $oldCronJob) { + if ($oldCronJob->id == $model->id) { + continue; + } + $allCronJobs[$oldCronJob->user][] = $oldCronJob->toArray(); + } + + $model->configureCronJobs($allCronJobs); }); } - public function configureCronJobs() + public function configureCronJobs($cronJobs) { - $getAll = self::all(); - if ($getAll->count() > 0) { - $users = []; - foreach ($getAll as $cron) { - $users[$cron->user][] = $cron->toArray(); - } - foreach ($users as $user => $cronJobs) { - $now = now(); - $cronContent = <<user; + $cronContent = << $cronJobs) { foreach ($cronJobs as $cronJob) { $cronContent .= $cronJob['schedule'] . ' ' . $cronJob['command'] . PHP_EOL; } - - $cronContent .= PHP_EOL; - $cronFile = '/tmp/crontab-' . $user; - file_put_contents($cronFile, $cronContent); - - $output = shell_exec('crontab -u ' . $user . ' ' . $cronFile); - unlink($cronFile); - } } + $cronContent .= PHP_EOL; + $cronFile = '/tmp/crontab-' . $user; + file_put_contents($cronFile, $cronContent); + + $output = shell_exec('crontab -u ' . $user . ' ' . $cronFile); + unlink($cronFile); + return false; }