Skip to content

Add crontab:remove task to contrib/crontab.php #4033

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions contrib/crontab.php
Original file line number Diff line number Diff line change
Expand Up @@ -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' : '';
Expand Down
8 changes: 8 additions & 0 deletions docs/contrib/crontab.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.