How To Execute and List Cron Jobs for a Linux System via PHP

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

This article will guide you through the process of executing and listing cron jobs for a Linux system via PHP.

The “cron job php script” is a cron job that will list all the cron jobs for a Linux system. This can be done by executing the following command in PHP. The result of this command will be an array with the name, time, and status of each cron job along with their respective process ID number.

How To Execute and List Cron Jobs for a Linux System via PHP

Working with cron tasks manually is most usual when there are a small number of them. But what if you’re managing a large number of cron jobs? PHP is the solution! What is PHP’s purpose? Because it can automate the activities of adding, removing, and Cron Job Postings.

In this lesson, you’ll discover how PHP may help you save time on a Linux system by automating the addition, removal, and listing of cron tasks.

Ready? Let’s get started!

Prerequisites

This will be a hands-on presentation in this course. If you want to follow along, make sure you have the following items on hand:

  • Crontab — By default, Crontab is installed on Linux operating systems.
  • The cron system is used by almost all Linux distributions. The samples are shown on a macOS machine with a BSD-based operating system.

How to Make a Crontab File

You’ll need a file to hold your cron tasks before you can manage them. All cron tasks are recorded in a single crontab file that is used by the whole system.

To change your directory to /usr/local and create subdirectories, open your terminal and type the commands below (jobs and scripts). You may call these directories anything you like. Later, your cron job files and scripts will be stored in these folders.

cd /usr/local && sudo mkdir jobs scripts

To generate the crontab file, execute the command below (crontab -e). When you run the crontab command for the first time, it creates a crontab file in your /tmp directory.

# Sets nano export as the default text editor. # EDITOR=’nano’ EDITOR=’nano’ EDITOR=’nano crontab -e crontab -e crontab -e crontab -e crontab -e crontab -e crontab -e crontab

How to Use a Real PowerShell Text Editor to Edit Files

Adding Jobs to a Single Cron

You may start controlling your cron tasks now that you’ve established the crontab file. However, you must first concentrate on adding them using PHP. How? To add cron jobs, you’ll write and run a PHP script.

As indicated below, cron tasks are scheduled using five parameters. Whether for hourly, daily, weekly, or monthly cron jobs, each parameter has a default value of *, indicating that no value was supplied for that parameter.

<minute> <hour> <day(month)> <month> <day(week)> <command-line operation>

Take a peek at crontab’s webpage for a refresher on cron job syntax with examples.

1. In your text editor, create a file and paste the code below into it. Save it in the /usr/local/jobs directory. The file is titled newjob.py in this example, but you may call it anything you like. When the code below is run, it outputs the text (Executed!)

2. Next, create a PHP script file and put the code below into it, saving it in the /usr/local/scripts directory. The script is called add.php in this tutorial.

Remember to store the script files in the /usr/local/scripts directory and the cron job files in the /usr/local/jobs directory throughout the course.

The code below adds the newjob.py file to the crontab file as a cron job.

<?php // sort – Sorts the string in memory alphabetically. // uniq – Removes any duplicate cron jobs from the string in memory. // crontab – Writes the string in memory to the crontab file shell_exec(“(crontab -l ; echo ‘* * * * * python3 /usr/local/jobs/newjob.py’) | sort | uniq | crontab”); ?>

Before creating a new cron job, the shell exec action saves the list of current cron jobs to a string in memory, ensuring that none of the existing cron tasks are lost.

Is shell exec not working for you? This function might be deactivated in your php.ini file. Look in your php.ini for the disable functions option and remove shell exec from the list. Keep in aware that this feature might be exploited, so exercise caution!

3. Execute the add.php script from the /usr/local/scripts directory using the command below.

When running scripts throughout the lesson, make sure you’re in the /usr/local/scripts directory.

4. Finally, use the crontab -l command to see whether the new cron job has been created.

Cron Job Postings Cron Job Postings

Cron Job Postings

Perhaps you want to keep track of the cron jobs you’ve added, so you can either update or remove them. If so, your first step is to list the existing cron jobs. Cron Job Postings come in handy to keep track of the cron jobs you have.

Create a new PHP script, name it something unique, and put the code below into it. The script for this example is called list.php.

The shell exec action in the following code collects and shows (echo()) all cron jobs (crontab -l) from the crontab file.

<?php echo(shell_exec(“crontab -l”)); ?>

To run the list.php script, use the command below.

Using a PHP script to generate a list of Cron Jobs Using a PHP script to generate a list of Cron Jobs

Creating a List of Cron Jobs

Instead of a normal list, you may wish to output the list of cron tasks as an array. If that’s the case, you’ll need the explode() methods. These routines allow you to save cron tasks as an array element in the crontab file.

Replace the list.php file’s content with the code below. The code below outputs the string length of each cron job as well as an array of cron tasks.

<?php // Lists existing cronjobs as string $job_list = shell_exec(“crontab -l”); // Store the list of existing cron jobs ($job_list), // each in a new line (‘\n’) to the $cron_jobs variable $cron_jobs = explode(“\n”, $job_list); // Prints the list of array structured cron jobs ($cron_jobs) var_dump($cron_jobs); ?>

To run the list.php script, use the following command.

The code produces a list of cron tasks in an array, as well as the text length, as seen below.

Cron Job Postings in Array Cron Job Postings in Array

Cron Jobs are being phased out.

After you’ve compiled a list of existing cron tasks, you may determine what to do with each one. Perhaps you wish to get rid of certain cron tasks. If that’s the case, you’ll put the cron job you want to delete in a string variable.

1. For this example, create a new PHP script named remove.php and add the code below to it. You may name the script file anything you like.

The code below deletes a cron task from the crontab file.

<?php # Stores the list of cron jobs as string to $jobs variable $jobs = shell_exec(“crontab -l”); # Defines the $to_remove string as the cron job to remove $to_remove = “* * * * * php /usr/local/scripts/newjob.php”; # Removes the cron job ($to_remove) from the list of cron jobs ($jobs) # and stores the new list of cron jobs inside the $removed string. $removed = str_replace($to_remove,””,$jobs); # Writes the $removed string value to the crontab file. shell_exec(“echo ‘$removed’ | sort | uniq | crontab”); ?>

2. To run the remove.php script, type the following command.

3. Finally, use the crontab -l command to verify that the newjob.php cron job has been deactivated. crontab -l crontab -l crontab -l

Verifying newjob.php has been deactivated. Verifying newjob.php has been deactivated.

Multiple Cron Jobs Can Be Added and Removed

You may add many cron jobs to a single cron job, which is useful if you have a lot of daily chores to automate. How? You may do this by including a for loop in your script.

Multiple Cron Jobs Can Be Added and Removed share a similar approach, but the script to remove multiple cron jobs has more use of variables, as demonstrated below.

1. In your add.php file, replace the text with the code below. By swimming through an array, the code below adds several cron tasks to the crontab file.

<?php // Define cron jobs (three) as string separated by commas $to_add = [“* * * * * php /usr/local/scripts/newjob.py”, “* * * * * node /usr/local/scripts/newjob2.js”, “* * * * * -ls”]; // Loops three times adding cron jobs to the crontab file // since you defined three cron jobs as string for ($i = 0; $i < 3; $i++) { shell_exec(“(crontab -l ; echo ‘”.$to_add[$i].”‘) | sort | uniq | crontab”); } ?>

2. Then, to execute the add.php script, perform the command below. php add.php

3. Use the crontab -l command to see whether the cron jobs you added to the crontab file are still active. crontab -l crontab -l crontab -l

Verifying Multiple Cron Jobs Have Been Added Verifying Multiple Cron Jobs Have Been Added

4. Now, in your remove.php file, replace the text with the code below, which eliminates all of the cron jobs you specified. Similar to creating numerous cron jobs, deleting multiple cron jobs follows the same procedure, but with a few more variables.

<?php // Define cron jobs (three) as string separated by commas $to_remove = [“* * * * * php /usr/local/scripts/newjob.py”, “* * * * * node /usr/local/scripts/newjob2.js”, “* * * * * -ls”]; // Executes the shell_exec command three times to remove cron jobs for ($i = 0; $i < 3; $i++) { // List existing cron jobs as string $jobs = shell_exec(“crontab -l”); // Collects cron jobs to remove from the existing cron jobs in an array $removed = str_replace($to_remove[$i],””,$jobs); // Removes cron jobs ($removed) shell_exec(“echo ‘$removed’ | sort | uniq | crontab”); } ?>

5. To run the remove.php script, type the following command.

6. Finally, use the crontab -l command to double-check that the cron tasks have been eliminated.

You won’t receive an output like this if you’ve successfully eliminated the cron tasks.

Cron Jobs are no longer available. Cron Jobs are no longer available.

Creating Cron Job Management Functions

So far, you’ve seen how to use distinct scripts to create, delete, and list cron tasks. However, instead of executing three different scripts, you may build functions in a single script to handle cron tasks more efficiently.

Copy the code below into a new script file. You may call the script anything you like, but for this example, we’ll call it multi.php.

With three different methods that you may call at the bottom of the script, the code below creates, removes, and lists cron jobs.

<?php # Adds a crob job to the crontab file function add_job(){ shell_exec(“(crontab -l ; echo ‘* * * * * php /usr/local/scripts/newjob.py’) | sort | uniq | crontab”); } # Removes a crob job from the crontab file function remove_job(){ $jobs = shell_exec(“crontab -l”); $to_remove = “* * * * * php /usr/local/scripts/oldjob.php”; $removed = str_replace($to_remove,””,$jobs); shell_exec(“echo ‘$removed’ | sort | uniq | crontab”); } # Lists existing cron jobs function list_jobs(){ echo(shell_exec(“crontab -l”)); } // CALL THE FUNCTIONS HERE // Call the functions that adds and removes cron jobs but provide no output add_job() remove_job() // Calls the function that outputs a list all exiting cron jobs list_jobs() ?>

To run the multi.php script, use the command below.

The result of the list jobs() method in the multi.php script is shown below.

The multi.php script is being run. The multi.php script is being run.

Memory Overload Prevention

You’ve seen PHP’s cron management tools, but having too many cron tasks eats up memory. How can you keep your memory from being overburdened? Limit the number of cron jobs you may add to the crontab file.

1. In the multi.php script, add the following method. The code below counts all cron jobs by counting all lines in the crontab file and outputs a message to let you know how many cron jobs are currently running.

count jobs function () $jobs = shell exec(“crontab -l”); $jobs = shell exec(“crontab -l”); $jobs = shell exec(“crontab echo(“You currently have “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, “, ” $jobs, “n”); substr count($jobs, “n”); “cron jobs”); ” cron jobs”); ” cron jobs”); ” cron jobs”);

2. Next, call the count_jobs() function at the end of the script, as you did in the “Creating Cron Job Management Functions” section.

3. To run the multi.php script, use the following command.

As you can see in the screenshot below, a notification informs you of the current cron job count.

Executing the multi.php script, which displays the current Cron Job Count. Executing the multi.php script, which displays the current Cron Job Count.

However, if there are too many cron jobs running at the same time, you may wish to automatically end the script. If that’s the case, an if condition will suffice.

4. In the multi.php file, replace the count jobs() method with the one below.

The function below reads the number of lines in the crontab file and chooses whether or not to terminate the script depending on that number.

function count_jobs(){ $jobs = shell_exec(“crontab -l”); # Counts all cron jobs from the crontab file and prints the result echo(“You currently have “.substr_count( $jobs, “n”).” cron jobsn”); # Checks whether the cron jobs count is over 50 or not if(substr_count( $jobs, “n”) > 50){ # Prints a message and terminates the script exit(“Too many cron jobs, cannot add any more!”); } }

5. Finally, run the multi.php script, just like you did in step three.

The message that shows you how many cron tasks are currently running can be seen in the output below (63). Because there are more than 50 cron tasks, the script will immediately end rather than continue creating cron jobs.

When the Cron Jobs Count Limit is reached, the script is terminated. When the Cron Jobs Count Limit is reached, the script is terminated.

Conclusion

The shell exec() function in PHP offers a mechanism to automate cron tasks, as you’ve seen throughout this article. You’ve learned how to use a single PHP script to create, delete, and list cron tasks while avoiding memory overload.

Will you think about PHP the next time you need to handle cron tasks for one of your projects?

The “create scheduled task using php” is a process that allows users to execute and list cron jobs for a Linux system. The process is done via PHP.

Related Tags

  • cron job in php w3schools
  • how to automate php script
  • php edit crontab
  • run php file cron job ubuntu
  • cron job cpanel php

Table of Content