Add cron jobs

This commit is contained in:
Bozhidar 2024-04-24 23:16:26 +03:00
parent c07cd6da45
commit 134fa9932b

View file

@ -17,28 +17,47 @@ class CronJob extends Model
{
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();
$user = $this->user;
$cronContent = <<<EOT
# PhyrePanel Cron Jobs
# User: $user
@ -47,9 +66,13 @@ class CronJob extends Model
EOT;
$cronContent .= PHP_EOL . PHP_EOL;
if (!empty($cronJobs)) {
foreach ($cronJobs as $user => $cronJobs) {
foreach ($cronJobs as $cronJob) {
$cronContent .= $cronJob['schedule'] . ' ' . $cronJob['command'] . PHP_EOL;
}
}
}
$cronContent .= PHP_EOL;
$cronFile = '/tmp/crontab-' . $user;
@ -58,9 +81,6 @@ class CronJob extends Model
$output = shell_exec('crontab -u ' . $user . ' ' . $cronFile);
unlink($cronFile);
}
}
return false;
}