diff --git a/contrib/crontab.php b/contrib/crontab.php index 92cece25a..93bc8972e 100644 --- a/contrib/crontab.php +++ b/contrib/crontab.php @@ -81,6 +81,49 @@ setRemoteCrontab($cronJobs); }); +desc('Remove crontab jobs'); +task('crontab:remove', function () { + $cronJobsLocal = array_map( + fn($job) => parse($job), + get('crontab:jobs', []), + ); + + $cronJobs = getRemoteCrontab(); + $identifier = get('crontab:identifier'); + $sectionStart = "###< $identifier"; + $sectionEnd = "###> $identifier"; + + // Find our cronjob section + $start = array_search($sectionStart, $cronJobs); + $end = array_search($sectionEnd, $cronJobs); + + if ($start && $end) { + // Remove the existing section + array_splice($cronJobs, $start + 1, $end - $start - 1); + writeln("Crontab: Found existing section, removed jobs"); + } elseif (count($cronJobsLocal) > 0) { + $foundJobs = false; + // Remove individual jobs if no section is present + foreach ($cronJobs as $index => $cronJob) { + if (in_array($cronJob, $cronJobsLocal)) { + unset($cronJobs[$index]); + $foundJobs = true; + } + } + if ($foundJobs) { + writeln("Crontab: Found existing jobs in crontab, removed jobs"); + } else { + writeln("Crontab: No existing jobs in crontab, skipping"); + return; + } + } else { + writeln("Crontab: Found no section and crontab:jobs is not configured, skipping"); + return; + } + + setRemoteCrontab($cronJobs); +}); + function setRemoteCrontab(array $lines): void { $sudo = get('crontab:use_sudo') ? 'sudo' : ''; diff --git a/docs/contrib/crontab.md b/docs/contrib/crontab.md index 01f43c3be..596acaf66 100644 --- a/docs/contrib/crontab.md +++ b/docs/contrib/crontab.md @@ -82,3 +82,11 @@ Sync crontab jobs. +### crontab\:remove {#crontab-remove} +[Source](https://github.com/deployphp/deployer/blob/master/contrib/crontab.php#L85) + +Remove crontab jobs. + + + +