Skip to content

Commit 8938eb2

Browse files
authored
Add crontab:remove task to contrib/crontab.php (#4033)
* add crontab:remove task to contrib/crontab.php * updated docs * fix code style errors --------- Co-authored-by: Ray Gesualdo <rgesualdo@slack-corp.com>
1 parent 5f69a2e commit 8938eb2

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

contrib/crontab.php

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,49 @@
8181
setRemoteCrontab($cronJobs);
8282
});
8383

84+
desc('Remove crontab jobs');
85+
task('crontab:remove', function () {
86+
$cronJobsLocal = array_map(
87+
fn($job) => parse($job),
88+
get('crontab:jobs', []),
89+
);
90+
91+
$cronJobs = getRemoteCrontab();
92+
$identifier = get('crontab:identifier');
93+
$sectionStart = "###< $identifier";
94+
$sectionEnd = "###> $identifier";
95+
96+
// Find our cronjob section
97+
$start = array_search($sectionStart, $cronJobs);
98+
$end = array_search($sectionEnd, $cronJobs);
99+
100+
if ($start && $end) {
101+
// Remove the existing section
102+
array_splice($cronJobs, $start + 1, $end - $start - 1);
103+
writeln("Crontab: Found existing section, removed jobs");
104+
} elseif (count($cronJobsLocal) > 0) {
105+
$foundJobs = false;
106+
// Remove individual jobs if no section is present
107+
foreach ($cronJobs as $index => $cronJob) {
108+
if (in_array($cronJob, $cronJobsLocal)) {
109+
unset($cronJobs[$index]);
110+
$foundJobs = true;
111+
}
112+
}
113+
if ($foundJobs) {
114+
writeln("Crontab: Found existing jobs in crontab, removed jobs");
115+
} else {
116+
writeln("Crontab: No existing jobs in crontab, skipping");
117+
return;
118+
}
119+
} else {
120+
writeln("Crontab: Found no section and crontab:jobs is not configured, skipping");
121+
return;
122+
}
123+
124+
setRemoteCrontab($cronJobs);
125+
});
126+
84127
function setRemoteCrontab(array $lines): void
85128
{
86129
$sudo = get('crontab:use_sudo') ? 'sudo' : '';

docs/contrib/crontab.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,3 +82,11 @@ Sync crontab jobs.
8282

8383

8484

85+
### crontab\:remove {#crontab-remove}
86+
[Source](https://github.com/deployphp/deployer/blob/master/contrib/crontab.php#L85)
87+
88+
Remove crontab jobs.
89+
90+
91+
92+

0 commit comments

Comments
 (0)