php and cron jobs

What are cron jobs?

The name “cron” comes from the Greek word “chronos,” meaning time, and it is a powerful tool for automating routine operations on a server or system.

Imagine you have a to-do list of tasks you need to do regularly, like sending a reminder email or backing up your computer. Some of these tasks are needed at specific times, like sending that email every day at 3 PM, while others might need to happen weekly or monthly. Cron jobs are task scheduler for your computer. They help you automate these tasks at the right times without you having to remember to do them yourself.

Cron jobs are a time-based job scheduler in Unix-like operating systems. They allow you to automate tasks at specific times or on a recurring schedule. Cron jobs are defined in crontab files, and they are used to schedule repetitive tasks, such as running scripts, executing commands, or performing system maintenance at predefined intervals.

Common settings for cron jobs

Adding a cron job to your hosting cPanel involves a specific procedure. To successfully set up a cron job in your hosting cPanel, follow these steps:

  1. Access Cron Jobs in cPanel: Begin by logging into your cPanel. If you have a hosting provider account, log in to your hosting provider account and navigate to cPanel. Once inside cPanel, you’ll land on the dashboard. Scroll down to find the “Advanced” section, where you can locate the “Cron Jobs” option. Alternatively, you can use the search box within cPanel to find the “Cron Jobs” option.
  2. Configuring the Cron Job: Setting up a cron job is a straightforward process. In the cPanel, use the drop-down lists to specify your desired settings. There are different fields to fill in:
    1. Minutes: Enter the specific minute when you want the cron job to execute.
    2. Hour: Set the hour for the cron job to run.
    3. Day: Define the day of the month for the cron job.
    4. Month: Specify the month for the cron job.
    5. Weekday: Indicate the specific day of the week for the cron job.
    6. Command: If you want the cron job to perform a specific task or send a particular message, input the command, and it will execute according to your instructions each time it runs.

How to set up a php cron job?

Step 1: Access Cron Jobs in cPanel

Begin by logging into your cPanel. If you have a hosting provider account, log in to your hosting provider account and navigate to cPanel. Once inside the cPanel, you’ll land on the dashboard. Scroll down to find the “Advanced” section, where you can locate the “Cron Jobs” option. Alternatively, you can use the search box within cPanel to find the “Cron Jobs” option.

Step 2: Ready your php script

Here is the php script that will send an email to your desired email address from the email account set in you cPanel, in this case I will be using the hosting service provided in my sushilparajuli.com website with the php script that sends an email from testphp@sushilparajuli.com every minute my gmail address. 

            <?php
$name='Testing PHP Emailer';
$email='testphp@sushilparajuli.com'; 
$msg='This is an automated email from a cron job'; 
$phone=''; 
$FromName="Test PHP Emailer";
$FromEmail="testphp@sushilparajuli.com"; // set your cpanel email 
$ReplyTo=$email;
$toemail="youremail@gmail.com"; // set to email 
$subject="New message from Cron Job"; 
$message='Name:-'.$name.'<br>Email :-' .$email.'<br> Phone No:-'.$phone.'<br> Message:-'.$msg;
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
$headers .= "From: ".$FromName." <".$FromEmail.">\n";
$headers .= "Reply-To: ".$ReplyTo."\n";
$headers .= "X-Sender: <".$FromEmail.">\n";
$headers .= "X-Mailer: PHP\n";
$headers .= "X-Priority: 1\n";
$headers .= "Return-Path: <".$FromEmail.">\n";
   if(mail($toemail, $subject, $message, $headers,'-f'.$FromEmail) ){
          $hide=1;
         echo '<div class="success"><center><span style="font-size:100px;">✅</span></center> <br> Thank you <strong>'.$name.',</strong> Your message has been sent. </div> '; 
	} else {
		echo "The server failed to send the message.";
} 	
?> 
        

Step 3: Configure the settings for your cron job

I want my cron job to be automatically executed once per minute so my time settings would be (* * * * *) – the settings are pretty straight forward and the shortcodes for the scheduling settings are usually provided in the cpanel settings itself. 

Step 4: Setup the cron command

The cron command is set using the following syntax: 

            php -q /home2/sushilpa/public_html/testphp/phpemailer.php
        

Here –
sushilpa – is an account username. Replace this with your own cPanel username.
public_html – is the root folder.
testphp – a folder inside the root folder where your php file is located

Step 5: Monitor your result

Once this cron job is set up, it automatically executes every minute and sends a mail to the email address that you set up. 

Benefits of cron jobs

Cron jobs are versatile and can be used to automate a wide range of tasks and tools on a computer or server. It can help us create 

  1. Email Notifications: Send automated email notifications or alerts for specific events or server conditions. 
  2. Data Processing: Run scripts or programs to process data, like converting file formats or cleaning up data. 
  3. Report Generation: Generate and send reports at specific intervals, like daily, weekly, or monthly.
  4. Content Publishing: Publish content on websites or blogs at specific times, like scheduling blog posts.
  5. Social Media Posting: Schedule social media posts and updates for marketing purposes.
  6. Scheduled Backups: You can set up cron jobs to create regular backups of your data, databases, or server configurations.
  7. Data Synchronization: Automate data synchronization processes, such as copying files from one location to another.
  8. Log Rotation: Rotate and manage log files to prevent them from filling up your storage. Perform tasks like clearing cache, updating website content, or checking for broken links.
  9. Resource Monitoring: Monitor server resource usage and take actions based on thresholds, like restarting services when necessary.
  10. Scheduled Tasks for Applications: Many applications use cron jobs for their scheduled tasks, such as WordPress for publishing content or database maintenance.