Difference between revisions of "Crons"

From WHMCS Documentation

(Change of Daily Cron Hour)
(Task Options for skip and do)
 
(43 intermediate revisions by 7 users not shown)
Line 1: Line 1:
Cron tasks must be created to automate tasks within WHMCS.
+
<div class="docs-alert-info">Need to troubleshoot the cron? Check out our [https://help.whmcs.com/m/automation/l/683269-advanced-cron-troubleshooting| Advanced Cron Troubleshooting Guide.]</div>
  
Cron is the name given to a system daemon used to execute tasks (in the background) at designated times. WHMCS has a number of files that are required to be run on a periodic basis in this way. All these files are located in the ''crons'' directory.
+
You must create cron tasks in order to automate tasks within WHMCS.
 +
 
 +
The cron is a system daemon used to execute tasks at designated times. WHMCS includes processes that must run on a periodic basis via the cron. All of these files are in the <tt>crons</tt> directory.
  
 
==Setting up the Cron Tasks==
 
==Setting up the Cron Tasks==
Line 7: Line 9:
 
===System Cron===
 
===System Cron===
  
The system cron automates tasks within WHMCS. It should be configured as follows:
+
The system cron automates tasks within WHMCS. Configure this to use the appropriate frequencies:
  
 
<table class="table table-bordered">
 
<table class="table table-bordered">
 
<tr><th>Version</th><th>System Cron Frequency</th></tr>
 
<tr><th>Version</th><th>System Cron Frequency</th></tr>
<tr><td>WHMCS 6.3.x and earlier</td><td>Once per day</td></tr>
+
<tr><td>WHMCS 6.3.x and earlier</td><td>Once per day.</td></tr>
<tr><td>WHMCS 7.0 and later</td><td>Every 5 minutes, or as frequently as your web hosting provider allows (minimum once per hour)</td></tr>
+
<tr><td>WHMCS 7.0 and later</td><td>Every 5 minutes, or as frequently as your hosting provider allows (minimum once per hour).</td></tr>
 
</table>
 
</table>
  
Line 20: Line 22:
 
</source>
 
</source>
  
You can find a copy&paste ready command with the path specific for your setup by navigating to ''Setup > Automation Settings'' within your WHMCS installation and copying the command from the "Create the following Cron Job using PHP" field.
+
You can find the correct command to copy-and-paste for your WHMCS installation by navigating to '''Configuration (<i class="fa fa-wrench" aria-hidden="true"></i>) > System Settings > [[Automation Settings]]''' and clicking on the first badge. Prior to WHMCS 8.0, visit '''Setup > Automation Settings'''.  
  
<div class="docs-alert-success">Most web hosting control panels provide a simple user interface for creating cron jobs. We have guides and documentation for most popular control panels [[Cron Configuration|available here]].</div>
+
[[File:Cron-configuration-badge.png|border]]
 +
 
 +
<div class="docs-alert-success">Most hosting control panels provide a simple user interface for creating cron jobs. For more information, see [[Cron Configuration]].</div>
  
 
===Domain Sync Cron===
 
===Domain Sync Cron===
<div class="docs-alert-warning"><i class="fa fa-question-circle"></i> This cron is only required in 7.5 and earlier. It should be removed in 7.6 and above</div>
+
<div class="docs-alert-warning"><i class="fa fa-question-circle"></i>This cron task is only required in WHMCS 7.5 and earlier. Remove it in WHMCS 7.6 and later.</div>
 
 
This cron task monitors for incoming domain transfers and synchronises expiry date changes made directly at a registrar.  We recommend running this no more frequently than once every couple of days.  More information is available at [[Domains_Tab#Domain_Sync_Enabled]] and [[Domain Synchronisation]]
 
  
 +
This cron task monitors incoming domain transfers and synchronises expiry date changes made directly at a registrar. We only recommend running this every few days. More information is available at [[Domains_Tab#Domain_Sync_Enabled|Domain Sync Enabled]] and [[Domain Synchronisation]].
  
 
'''Sample Cron Command'''
 
'''Sample Cron Command'''
Line 35: Line 38:
 
</source>
 
</source>
  
The above example will run every 2 days at 3am.
+
The above example will run at 3 a.m. every two days.
  
 
===POP Email Import Cron===
 
===POP Email Import Cron===
  
This cron task is only required if you wish to import emails to the support queue via the POP3 protocol (we recommend using [[Email Piping]] wherever possible)If required, this should be configured to run every 5 minutes.
+
This cron task is only required if you wish to import emails to the support queue via the POP3 protocol. (We recommend using [[Email Piping]] instead.) If you use this, configure it to run every five minutes.
  
 
'''Sample Cron Command'''
 
'''Sample Cron Command'''
Line 46: Line 49:
 
</source>
 
</source>
  
The above example will run the POP3 email import task every 5 minutes.
+
The above example will run the POP3 email import task every five minutes.
  
 
===Change of Daily Cron Hour===
 
===Change of Daily Cron Hour===
  
The desired time of day for the daily automated actions to be executed can be changed via the "Time of Day" setting detailed in our [[Automation_Settings]] documentation.  
+
You can change the time at which the daily automated actions run using the '''Time of Day''' setting. For more information, see [[Automation Settings]].
  
WHMCS uses the PHP "now()" timestamp when the cron.php script is run to determine the current time. The calculation as to whether it is currently the "Time of Day" hour is based upon the value output by the PHP configuration applied the cron.php execution.
+
WHMCS uses the PHP <tt>now()</tt> timestamp when the <tt>cron.php</tt> script runs. This determines the current '''Time of Day''' based on the value that the PHP configuration returns applied to the <tt>cron.php</tt> execution.
  
We recommend executing the cron every 5 minutes. WHMCS will never perform a particular task more frequently than advised here: [https://docs.whmcs.com/Crons#Task_Options_for_skip_.26_do Crons - Task Options for skip]. Hence it is the cron.php file can be triggered every 5 minutes without any duplication occurring.
+
We recommend executing the cron task every 5 minutes. WHMCS will never perform a particular task more frequently than [[Crons#Task_Options_for_skip_.26_do Crons - Task Options for skip|they are listed here]]. You can set the <tt>cron.php</tt> file to run every 5 minutes without any duplication.
  
If you do want to execute cron.php only at the hour specified in the "Time of Day" setting, ensure the timezone WHMCS is operating under matches that of the server's command line. More information on this can be found in the [[Changing_Timezone]] documentation.
+
If you only want to execute <tt>cron.php</tt> at the "Time of Day" hour, ensure that WHMCS's configured time zone matches the server's time zone. For more information, see [[Changing_Timezone]].
  
<div class="docs-alert-warning">The cron must execute the cron.php file within the hour set in the automation settings of WHMCS  otherwise the daily automated tasks won't be performed.</div>
+
<div class="docs-alert-warning">The cron must execute the <tt>cron.php</tt> file within the hour that you set in WHMCS's automation settings. If it does not, the daily automated tasks will not run.</div>
  
==Secure The Crons Directory==
+
==Secure The crons Directory==
  
The crons folder may be moved to any place above or below the docroot.
+
You can move the <tt>crons</tt> folder to any location above or below the document root.
  
<div class="docs-alert-warning">We recommend moving it to a non-public directory above your web root to prevent web based access.</div>
+
<div class="docs-alert-warning">We recommend moving it to a private directory above your document root. This helps to prevent access by bad actors.</div>
  
More information on moving the crons folder can be found in the [[Custom Crons Directory|Custom Crons Directory article]].
+
For more information, see [https://help.whmcs.com/m/installation/l/1650302-moving-the-crons-directory Moving the Crons Directory].
  
 
==System Cron==
 
==System Cron==
  
The system cron (''crons/cron.php'') automates tasks within WHMCS. This script can be executed with a number of optional values. This allows very specific control of the tasks performed and the output generated by the script. For most installations, a simple entry that invokes the System Cron script (''crons/cron.php'') is all that is needed.
+
The system cron (<tt>crons/cron.php</tt>) automates tasks within WHMCS. This script can run with several optional values. This allows very specific control of the tasks that run and the script's output. Most WHMCS installations only require an entry that invokes the system cron script (<tt>crons/cron.php</tt>).
  
 
===Input===
 
===Input===
Line 77: Line 80:
  
 
<source lang="cli">
 
<source lang="cli">
cron.php [<command> [options]]
+
cron.php [<argument> [options]]
 
</source>
 
</source>
  
The script also provides backwards capability for input options available prior to WHMCS v7.1:
+
The script also provides backwards capability for input options available prior to WHMCS 7.1:
  
 
<source lang="cli">
 
<source lang="cli">
Line 86: Line 89:
 
</source>
 
</source>
  
Mixing of legacy option flags with the new argument options is not supported and will not work.
+
Mixing legacy option flags with the current argument structure is '''not''' supported and will '''not''' work.
  
===Commands===
+
===Arguments===
  
The cron.php command line script has 3 essential commands:
+
The <tt>cron.php</tt> script includes three essential arguments:
  
* '''all''' - attempt to perform all due automation tasks. If no input is provided, this command is assumed.
+
* <tt>all</tt> — Attempt to perform all due automation tasks. If you do not provide input, this argument is applied by default.
* '''skip''' - perform all tasks, just like the '''all''' command, but exclude those specified in the input
+
* <tt>skip</tt> — Perform all tasks (in the same way as the <tt>all</tt> argument) but exclude tasks that you specify.
* '''do''' - only perform, unconditionally, the task(s) specified in the input options
+
* <tt>do</tt> — Only perform the tasks that you specify.
  
There are two supporting commands:
+
There are two supporting arguments:
  
* '''help''' - provides usage help & options for the command specified
+
* <tt>help</tt> — Lists help and options for the argument you specify.
* '''list''' - list all possible commands
+
* <tt>list</tt> — Lists all possible arguments.
  
 
===Options===
 
===Options===
  
Each command has its own set of options which can be view with the ''help <command>'' input syntax
+
Each argument has its own set of options, which you can view using <tt>help <argument></tt>.
  
 
====Additional Options====
 
====Additional Options====
Line 112: Line 115:
 
** Verbosity of command line output
 
** Verbosity of command line output
 
* --email-report=[1|0]
 
* --email-report=[1|0]
** Force send a digest report of work performed during execution. During the normal "daily" run, this is set to an implicit value of "1". In all other cases, the implicit value is "0"
+
** Force send a digest report of work performed during execution. During the normal "daily" run, this is set to an implicit value of "1". In all other cases, the implicit value is "0"
 
* -V, --version
 
* -V, --version
 
** Output the WHMCS version and exits
 
** Output the WHMCS version and exits
Line 122: Line 125:
 
===Output===
 
===Output===
  
The System Cron will not generate any success console output by default. Use the verbosity options if you require progressive completion information while attending the manual execution of System Cron invocation.
+
The System Cron will not generate any success console output by default. Use the verbosity options if you require progressive completion information while attending the manual execution of System Cron invocation.
  
The System Cron will, by default, generate a Digest Email Report when performing the "Daily" group of tasks. This report can be forcibly generated for any particular invocation with the ''--email-report=1'' report. The Digest Email Report will only contain information related to that execution and will not contain aggregate information from prior executions. Please visit the [[Automation Status]] page in your Admin area to get an overview of daily aggregated work.
+
The System Cron will, by default, generate a Digest Email Report when performing the "Daily" group of tasks. This report can be forcibly generated for any particular invocation with the ''--email-report=1'' report. The Digest Email Report will only contain information related to that execution and will not contain aggregate information from prior executions. Please visit the [[Automation Status]] page in your Admin area to get an overview of daily aggregated work.
  
 
===Tasks===
 
===Tasks===
  
All routines of system cron (''cron.php'') are tasks. Most tasks are daily, and should only be run once a day. Some tasks benefit from running multiple times a day, such as ticket escalations or checking for WHMCS Updates. Other tasks should only run once a month, such as calculating overage usage and generating the respective invoices.
+
All routines of system cron (''cron.php'') are tasks. Most tasks are daily, and should only be run once a day. Some tasks benefit from running multiple times a day, such as ticket escalations or checking for WHMCS Updates. Other tasks should only run once a month, such as calculating overage usage and generating the respective invoices.
 
 
====Task Options for '''skip''' & '''do'''====
 
  
 +
====Task Options for '''skip''' and '''do'''====
 +
 
 
<div id="Option_Flags" style="visibility: hidden"></div>
 
<div id="Option_Flags" style="visibility: hidden"></div>
 
When performing a '''skip''' or '''do''' command, you can itemize which tasks are excluded or included respectively.
 
When performing a '''skip''' or '''do''' command, you can itemize which tasks are excluded or included respectively.
 
Below is a table that itemizes these task options, as well as their normal frequency.
 
Below is a table that itemizes these task options, as well as their normal frequency.
 
+
 
 
{| class="table"
 
{| class="table"
 
|-
 
|-
Line 143: Line 146:
 
! scope="col" style="width:10%"| Frequency
 
! scope="col" style="width:10%"| Frequency
 
|-
 
|-
| --CurrencyUpdateExchangeRates
+
| --AddLateFees
| updaterates
+
| latefees
| Update Currency Exchange Rates
+
| Apply Late Fees
 +
| Daily
 +
|-
 +
| --AffiliateCommissions
 +
| affcommissions
 +
| Process Delayed Affiliate Commissions
 +
| Daily
 +
|-
 +
| --AffiliateReports
 +
| affreports
 +
| Send Monthly Affiliate Reports
 +
| Monthly
 +
|-
 +
| --AutoClientStatusSync
 +
| clientstatussync
 +
| Synchronise Client Status
 +
| Daily
 +
|-
 +
| --AutoPruneTicketAttachments
 +
| n/a
 +
| Auto Remove Inactive Ticket Attachments. Batches of 1000
 +
| Hourly
 +
|-
 +
| --AutoSuspensions
 +
| suspensions
 +
| Processing Overdue Suspensions
 +
| Daily
 +
|-
 +
| --AutoTerminations
 +
| terminations
 +
| Process Overdue Terminations
 +
| Daily
 +
|-
 +
| --CancellationRequests
 +
| cancelrequests
 +
| Process Cancellation Requests
 
| Daily
 
| Daily
 
|-
 
|-
| --CurrencyUpdateProductPricing
+
| --CheckForWhmcsUpdate
| updatepricing
+
| n/a
| Update Product Prices for Current Rates
+
| Check for WHMCS Software Updates
 +
| As soon as every 8 hours
 +
|-
 +
| --CloseInactiveTickets
 +
| closetickets
 +
| Auto Close Inactive Tickets
 
| Daily
 
| Daily
 
|-
 
|-
Line 158: Line 201:
 
| Daily
 
| Daily
 
|-
 
|-
| --AddLateFees
+
| --CreditCardExpiryNotices
| latefees
+
| ccexpirynotices
| Apply Late Fees
+
| Sending Credit Card Expiry Reminders
 +
| Monthly
 +
|-
 +
| --CurrencyUpdateExchangeRates
 +
| updaterates
 +
| Update Currency Exchange Rates
 +
| Daily
 +
|-
 +
| --CurrencyUpdateProductPricing
 +
| updatepricing
 +
| Update Product Prices for Current Rates
 
| Daily
 
| Daily
 
|-
 
|-
| --ProcessCreditCardPayments
+
| --DatabaseBackup
| ccprocessing
+
| backups
| Process Credit Card Charges
+
| Create a database backup and deliver via FTP or email
 
| Daily
 
| Daily
 
|-
 
|-
| --InvoiceReminders
+
| --DataRetentionPruning
| invoicereminders
+
| n/a
| Generate daily reminders for unpaid and overdue invoice
+
| Process data retention pruning operation. 7.5+
 
| Daily
 
| Daily
 
|-
 
|-
Line 178: Line 231:
 
| Daily
 
| Daily
 
|-
 
|-
| --DomainExpirySync
+
| --DomainStatusSync
 
| n/a
 
| n/a
| Processing Domain Expiry Syncing for Active domains
+
| Processing Domain Status Syncing for Active domains. Batches of 50. Known as DomainExpirySync in 7.7 and earlier
 
| As soon as every hour
 
| As soon as every hour
 
|-
 
|-
Line 186: Line 239:
 
| n/a
 
| n/a
 
| Processing Domain Transfer Syncing for Pending Transfer domains
 
| Processing Domain Transfer Syncing for Pending Transfer domains
| As soon as every hour  
+
| As soon as every hour
 
|-
 
|-
| --CancellationRequests
+
| --EmailCampaigns
| cancelrequests
+
| n/a
| Process Cancellation Requests
+
| Update the status of Email Campaigns and schedule emails. Batches of 50
| Daily
+
| As soon as every 5 minutes
 
|-
 
|-
| --AutoSuspensions
+
| --EmailMarketer
| suspensions
+
| emailmarketing
| Processing Overdue Suspensions
+
| Process Email Marketer Rules
| Daily
 
|-
 
| --AutoTerminations
 
| terminations
 
| Process Overdue Terminations
 
 
| Daily
 
| Daily
 
|-
 
|-
Line 208: Line 256:
 
| Daily
 
| Daily
 
|-
 
|-
| --CloseInactiveTickets
+
| --InvoiceAutoCancellation
| closetickets
+
| n/a
| Auto Close Inactive Tickets
+
| Automatically cancel old overdue unpaid invoices. 8.10+
 
| Daily
 
| Daily
 
|-
 
|-
| --AffiliateCommissions
+
| --InvoiceReminders
| affcommissions
+
| invoicereminders
| Process Delayed Affiliate Commissions
+
| Generate daily reminders for unpaid and overdue invoice
 
| Daily
 
| Daily
 
|-
 
|-
| --AffiliateReports
+
| --OverageBilling
| affreports
+
| overagesbilling
| Send Monthly Affiliate Reports
+
| Process Overage Billing Charges and Generate Invoices
 
| Monthly
 
| Monthly
 
|-
 
|-
| --EmailMarketer
+
| --ProcessCreditCardPayments
| emailmarketing
+
| ccprocessing
| Process Email Marketer Rules
+
| Process Credit Card Charges
 
| Daily
 
| Daily
 
|-
 
|-
| --CreditCardExpiryNotices
+
| --ProcessEmailQueue
| ccexpirynotices
+
| n/a
| Sending Credit Card Expiry Reminders
+
| Process scheduled emails within Email Campaigns. Batches of 25
| Monthly
+
| As soon as every 5 minutes
 
|-
 
|-
| --UpdateServerUsage
+
| --ServerRemoteMetaData
| usagestats
+
| n/a
| Updating Disk & Bandwidth Usage Stats
+
| Auto Update Server Meta Data. Displayed on '''Configuration (<i class="fa fa-wrench" aria-hidden="true"></i>) > System Settings > [[Servers]]''' or, prior to WHMCS 8.0, '''Setup > Products/Services > Servers'''. 7.8+
| Daily
+
| Hourly
 
|-
 
|-
| --OverageBilling
+
| --ServerUsageCount
| overagesbilling
+
| n/a
| Process Overage Billing Charges and Generate Invoices
+
| Auto Update Server Usage Count. Displayed on '''Configuration (<i class="fa fa-wrench" aria-hidden="true"></i>) > System Settings > [[Servers]]''' or, prior to WHMCS 8.0, '''Setup > Products/Services > Servers'''. 7.8+
| Monthly
+
| Hourly
 
|-
 
|-
| --AutoClientStatusSync
+
| --SslReissues
| clientstatussync
+
| n/a
| Synchronise Client Status
+
| Process MarketConnect SSL certificate reissuances. 8.5+
 
| Daily
 
| Daily
 
|-
 
|-
| --UpdateDomainExpiryStatus
+
| --SslSync
 
| n/a
 
| n/a
| Update Domain Expiry Status for domains with a past Expiry Date
+
| Check validity of SSL Certificates on services and domains. Batches of 100. 7.7+
 
| Daily
 
| Daily
 +
|-
 +
| --TenantUsageMetrics
 +
| n/a
 +
| Auto Update Service Usage Data. Displayed when viewing Service within Client Area. 7.9+
 +
| Twice-daily
 
|-
 
|-
 
| --TicketEscalations
 
| --TicketEscalations
Line 258: Line 311:
 
| As soon as every 3 minutes
 
| As soon as every 3 minutes
 
|-
 
|-
| --CheckForWhmcsUpdate
+
| --UpdateDomainExpiryStatus
 
| n/a
 
| n/a
| Check for WHMCS Software Updates
+
| Update Domain Expiry Status for domains with a past Expiry Date
| As soon as every 8 hours
 
|-
 
| --DatabaseBackup
 
| backups
 
| Create a database backup and deliver via FTP or email
 
 
| Daily
 
| Daily
 
|-
 
|-
| --DataRetentionPruning
+
| --UpdateServerUsage
| n/a
+
| usagestats
| Process data rentention pruning operation
+
| Updating Disk & Bandwidth Usage Stats
 
| Daily
 
| Daily
 
|-
 
|-
Line 280: Line 328:
 
* '''Application''': Advances state of client data, such as orders, billing, and provisioning
 
* '''Application''': Advances state of client data, such as orders, billing, and provisioning
 
* '''System''': Provides software related functionality, such as generating backups or performing database normalization.
 
* '''System''': Provides software related functionality, such as generating backups or performing database normalization.
** The "DatabaseBackup" task is the only task option of the '''System''' type which can be included/excluded from execution. All other '''System''' type task options will be performed explicitly as required by WHMCS and thus do not have option flags.
+
** The "DatabaseBackup" task is the only task option of the '''System''' type which can be included/excluded from execution. All other '''System''' type task options will be performed explicitly as required by WHMCS and thus do not have option flags.
  
 
====Tasks & --force Option====
 
====Tasks & --force Option====
Line 286: Line 334:
 
The "--force" option does exactly that...it will force execute ''any'' application tasks (respective of the command ['''all''', '''skip''', '''do''']) regardless if the task is suppose to run once a day, a month, or at a time other than now.
 
The "--force" option does exactly that...it will force execute ''any'' application tasks (respective of the command ['''all''', '''skip''', '''do''']) regardless if the task is suppose to run once a day, a month, or at a time other than now.
  
* The '''all''' command with the "–force" flag will execute all application tasks, as if each one were due exactly now.
+
* The '''all''' command with the "--force" flag will execute all application tasks, as if each one were due exactly now.
 
* The '''skip''' command with the "--force" will first exclude the specified tasks (i.e., the ones provided as task option flags) and then operate on all other tasks as if each were due exactly now, similar to the '''all''' command.
 
* The '''skip''' command with the "--force" will first exclude the specified tasks (i.e., the ones provided as task option flags) and then operate on all other tasks as if each were due exactly now, similar to the '''all''' command.
* The '''do''' command is designed to only run the tasks specified (i.e., the ones provided as task option flags) and to run them immediately, thus the "-–force" option is always implied and is not a valid option.
+
* The '''do''' command is designed to only run the tasks specified (i.e., the ones provided as task option flags) and to run them immediately, thus the "--force" option is always implied and is not a valid option.
 
* The "--force" option has no effect on '''System''' type tasks (except "DatabaseBackup")
 
* The "--force" option has no effect on '''System''' type tasks (except "DatabaseBackup")
 
* The "--force" option has no effect on whether the Daily Digest Email Report is sent, that is controlled via the --email-report option.
 
* The "--force" option has no effect on whether the Daily Digest Email Report is sent, that is controlled via the --email-report option.
 +
 +
<div class="docs-alert-info">Passing arguments to PHP scripts requires the <tt>register_argc_argv</tt> directive to be enabled.</div>
  
 
====Advanced Task Scheduling====
 
====Advanced Task Scheduling====
  
In some environments or use-cases, having fine-grained control of one or more tasks is important. This is possible through a combination of multiple '''do''' and '''skip''' crontab entries.
+
In some environments or use-cases, having fine-grained control of one or more tasks is important. This is possible through a combination of multiple '''do''' and '''skip''' crontab entries.
Tasks performed as part of a '''do''' command will not have their internal scheduling tracking modified. This is to ensure the integrity of a normal invocation of the System Cron.
+
Tasks performed as part of a '''do''' command will not have their internal scheduling tracking modified. This is to ensure the integrity of a normal invocation of the System Cron.
 
If you want a particular task to only execute on a particular schedule, create a '''do''' command for that task and alter your main System Cron invocation to '''skip''' that task (all other non-itemized tasks will be performed on the WHMCS schedule in this '''skip''').
 
If you want a particular task to only execute on a particular schedule, create a '''do''' command for that task and alter your main System Cron invocation to '''skip''' that task (all other non-itemized tasks will be performed on the WHMCS schedule in this '''skip''').
 
Likewise, if you never wish to have a particular task executed, alter your System Cron entry to be a '''skip''' command with the option for that particular task.
 
Likewise, if you never wish to have a particular task executed, alter your System Cron entry to be a '''skip''' command with the option for that particular task.
Line 311: Line 361:
 
** Registered hooks receive one parameter argument:
 
** Registered hooks receive one parameter argument:
 
*** The task object that is about to be executed, which adheres to WHMCS\Scheduling\Task\TaskInterface
 
*** The task object that is about to be executed, which adheres to WHMCS\Scheduling\Task\TaskInterface
*** The return value of this hook is not inspected. However, if an exception is thrown, the task will not be executed, be marked as incomplete, and iteration to the next task will commence
+
*** The return value of this hook is not inspected. However, if an exception is thrown, the task will not be executed, be marked as incomplete, and iteration to the next task will commence
 
* PostAutomationTask
 
* PostAutomationTask
 
** Is invoked after each Application task
 
** Is invoked after each Application task
Line 317: Line 367:
 
*** The task object that was just executed, which adheres to WHMCS\Scheduling\Task\TaskInterface
 
*** The task object that was just executed, which adheres to WHMCS\Scheduling\Task\TaskInterface
 
*** The boolean state if the task executed without throwing an Exception
 
*** The boolean state if the task executed without throwing an Exception
*** The return value of this hook is not inspected. Any Exception thrown will be discarded
+
*** The return value of this hook is not inspected. Any Exception thrown will be discarded
 
* DailyCronJobEmail
 
* DailyCronJobEmail
 
** Fires during the daily cron run or when --email-report=1 is specified
 
** Fires during the daily cron run or when --email-report=1 is specified
Line 334: Line 384:
 
===Example Crontab Entries===
 
===Example Crontab Entries===
  
Below are examples that demonstrate the flexibility of the System Cron input options and how you could craft your crontab entry. For most WHMCS installation, you should just have one entry (Ex. 1).
+
Below are examples that demonstrate the flexibility of the System Cron input options and how you could craft your crontab entry. For most WHMCS installation, you should just have one entry (Ex. 1).
 
If you wish to disable certain tasks entirely, consider looking at the related functionality's documentation first to understand how your may be able optimize your WHMCS settings from the administration area and potential avoid unnecessary crontab entries.
 
If you wish to disable certain tasks entirely, consider looking at the related functionality's documentation first to understand how your may be able optimize your WHMCS settings from the administration area and potential avoid unnecessary crontab entries.
  
Line 355: Line 405:
 
</source>
 
</source>
  
Ex 4. Always skip ticket escalations and auto suspensions. Process ticket escalations Monday-Friday during business hours, at the top of the hour, and auto suspension Monday-Friday at the start of business:
+
Ex 4. Always skip ticket escalations and auto suspensions. Process ticket escalations Monday-Friday during business hours, at the top of the hour, and auto suspension Monday-Friday at the start of business:
  
 
<source lang="cli">
 
<source lang="cli">
Line 363: Line 413:
 
</source>
 
</source>
  
Ex 5. In some hosting environments, direct crontab entries are not permitted. The System Cron can be invoked through an HTTP request (provided the script is accessible within the docroot)
+
Ex 5. In some hosting environments, direct crontab entries are not permitted. The System Cron can be invoked through an HTTP request (provided the script is accessible within the docroot)
 
The follow demonstrates performing all tasks except DomainRenewalNotices and TicketEscalations
 
The follow demonstrates performing all tasks except DomainRenewalNotices and TicketEscalations
  
 
<source lang="cli">
 
<source lang="cli">
GET http://www.yourdomain.com/admin/cron.php?command=skip&options=DomainRenewalNotices,TicketEscalations
+
GET http://www.example.com/admin/cron.php?command=skip&options=DomainRenewalNotices,TicketEscalations
 
</source>
 
</source>
  
 
==Legacy Cron File Locations==
 
==Legacy Cron File Locations==
  
Prior to WHMCS Version 6, the automated task files were located across various directories. Please refer to the top of this page for the new locations of the cron files.
+
Prior to WHMCS version 6, the automated task files were located across various directories. From WHMCS version 6 onwards all cron files are now located in the '''crons''' directory by default.
  
To aide in the transition process to their new locations, Version 6.0 of WHMCS includes proxy files in the old locations that will allow all existing configured cron and piping commands to continue operating without any changes post upgrade to 6.0.
+
To aide in the transition process to their new locations, version 6.0 of WHMCS includes proxy files in the old locations that will allow all existing configured cron and piping commands to continue operating without any changes post-upgrade to 6.0.
  
However, we encourage you to update your cron and piping commands to use the new locations at your earliest convenience.
+
However, we encourage you to update your cron and piping commands to use the new locations prior to updating to Version 8.0.
  
The old locations are deprecated as of Version 6.0, and the proxy functionality will be removed in a future release. The proxy files and their proxy locations are:
+
The old locations are deprecated as of Version 6.0, and the proxy functionality is removed as of version 8.0. The proxy files and their proxy locations are:
  
* /admin/cron.php
+
* <tt>/admin/cron.php</tt>
* /pipe/pipe.php
+
* <tt>/pipe/pipe.php</tt>
* /pipe/pop.php
+
* <tt>/pipe/pop.php</tt>
  
 
<div class="docs-alert-info">If you do not require these proxy files, you can safely remove them from your installation.</div>
 
<div class="docs-alert-info">If you do not require these proxy files, you can safely remove them from your installation.</div>

Latest revision as of 13:55, 24 April 2024

Need to troubleshoot the cron? Check out our Advanced Cron Troubleshooting Guide.

You must create cron tasks in order to automate tasks within WHMCS.

The cron is a system daemon used to execute tasks at designated times. WHMCS includes processes that must run on a periodic basis via the cron. All of these files are in the crons directory.

Setting up the Cron Tasks

System Cron

The system cron automates tasks within WHMCS. Configure this to use the appropriate frequencies:

VersionSystem Cron Frequency
WHMCS 6.3.x and earlierOnce per day.
WHMCS 7.0 and laterEvery 5 minutes, or as frequently as your hosting provider allows (minimum once per hour).

Sample Cron Command

*/5 * * * * php -q /home/username/crons/cron.php

You can find the correct command to copy-and-paste for your WHMCS installation by navigating to Configuration () > System Settings > Automation Settings and clicking on the first badge. Prior to WHMCS 8.0, visit Setup > Automation Settings.

Cron-configuration-badge.png

Most hosting control panels provide a simple user interface for creating cron jobs. For more information, see Cron Configuration.

Domain Sync Cron

This cron task is only required in WHMCS 7.5 and earlier. Remove it in WHMCS 7.6 and later.

This cron task monitors incoming domain transfers and synchronises expiry date changes made directly at a registrar. We only recommend running this every few days. More information is available at Domain Sync Enabled and Domain Synchronisation.

Sample Cron Command

0 3 */2 * * php -q /home/username/crons/domainsync.php

The above example will run at 3 a.m. every two days.

POP Email Import Cron

This cron task is only required if you wish to import emails to the support queue via the POP3 protocol. (We recommend using Email Piping instead.) If you use this, configure it to run every five minutes.

Sample Cron Command

*/5 * * * * php -q /home/username/crons/pop.php

The above example will run the POP3 email import task every five minutes.

Change of Daily Cron Hour

You can change the time at which the daily automated actions run using the Time of Day setting. For more information, see Automation Settings.

WHMCS uses the PHP now() timestamp when the cron.php script runs. This determines the current Time of Day based on the value that the PHP configuration returns applied to the cron.php execution.

We recommend executing the cron task every 5 minutes. WHMCS will never perform a particular task more frequently than they are listed here. You can set the cron.php file to run every 5 minutes without any duplication.

If you only want to execute cron.php at the "Time of Day" hour, ensure that WHMCS's configured time zone matches the server's time zone. For more information, see Changing_Timezone.

The cron must execute the cron.php file within the hour that you set in WHMCS's automation settings. If it does not, the daily automated tasks will not run.

Secure The crons Directory

You can move the crons folder to any location above or below the document root.

We recommend moving it to a private directory above your document root. This helps to prevent access by bad actors.

For more information, see Moving the Crons Directory.

System Cron

The system cron (crons/cron.php) automates tasks within WHMCS. This script can run with several optional values. This allows very specific control of the tasks that run and the script's output. Most WHMCS installations only require an entry that invokes the system cron script (crons/cron.php).

Input

The system cron script has the following argument input structure:

cron.php [<argument> [options]]

The script also provides backwards capability for input options available prior to WHMCS 7.1:

cron.php [legacy_option_flags]

Mixing legacy option flags with the current argument structure is not supported and will not work.

Arguments

The cron.php script includes three essential arguments:

  • all — Attempt to perform all due automation tasks. If you do not provide input, this argument is applied by default.
  • skip — Perform all tasks (in the same way as the all argument) but exclude tasks that you specify.
  • do — Only perform the tasks that you specify.

There are two supporting arguments:

  • help — Lists help and options for the argument you specify.
  • list — Lists all possible arguments.

Options

Each argument has its own set of options, which you can view using help <argument>.

Additional Options

  • -F, --force
    • Force the execution of tasks, regardless of "due" or "in progress" state
  • -v, -vv, -vvv
    • Verbosity of command line output
  • --email-report=[1|0]
    • Force send a digest report of work performed during execution. During the normal "daily" run, this is set to an implicit value of "1". In all other cases, the implicit value is "0"
  • -V, --version
    • Output the WHMCS version and exits
  • --no-ansi
    • Strip any non-printing command line markup (used for color output)
  • -h, --help
    • Print help for a command; same as the help command itself

Output

The System Cron will not generate any success console output by default. Use the verbosity options if you require progressive completion information while attending the manual execution of System Cron invocation.

The System Cron will, by default, generate a Digest Email Report when performing the "Daily" group of tasks. This report can be forcibly generated for any particular invocation with the --email-report=1 report. The Digest Email Report will only contain information related to that execution and will not contain aggregate information from prior executions. Please visit the Automation Status page in your Admin area to get an overview of daily aggregated work.

Tasks

All routines of system cron (cron.php) are tasks. Most tasks are daily, and should only be run once a day. Some tasks benefit from running multiple times a day, such as ticket escalations or checking for WHMCS Updates. Other tasks should only run once a month, such as calculating overage usage and generating the respective invoices.

Task Options for skip and do

When performing a skip or do command, you can itemize which tasks are excluded or included respectively. Below is a table that itemizes these task options, as well as their normal frequency.

Option Legacy Option Description Frequency
--AddLateFees latefees Apply Late Fees Daily
--AffiliateCommissions affcommissions Process Delayed Affiliate Commissions Daily
--AffiliateReports affreports Send Monthly Affiliate Reports Monthly
--AutoClientStatusSync clientstatussync Synchronise Client Status Daily
--AutoPruneTicketAttachments n/a Auto Remove Inactive Ticket Attachments. Batches of 1000 Hourly
--AutoSuspensions suspensions Processing Overdue Suspensions Daily
--AutoTerminations terminations Process Overdue Terminations Daily
--CancellationRequests cancelrequests Process Cancellation Requests Daily
--CheckForWhmcsUpdate n/a Check for WHMCS Software Updates As soon as every 8 hours
--CloseInactiveTickets closetickets Auto Close Inactive Tickets Daily
--CreateInvoices invoices Generate Invoices Daily
--CreditCardExpiryNotices ccexpirynotices Sending Credit Card Expiry Reminders Monthly
--CurrencyUpdateExchangeRates updaterates Update Currency Exchange Rates Daily
--CurrencyUpdateProductPricing updatepricing Update Product Prices for Current Rates Daily
--DatabaseBackup backups Create a database backup and deliver via FTP or email Daily
--DataRetentionPruning n/a Process data retention pruning operation. 7.5+ Daily
--DomainRenewalNotices domainrenewalnotices Processing Domain Renewal Notices Daily
--DomainStatusSync n/a Processing Domain Status Syncing for Active domains. Batches of 50. Known as DomainExpirySync in 7.7 and earlier As soon as every hour
--DomainTransferSync n/a Processing Domain Transfer Syncing for Pending Transfer domains As soon as every hour
--EmailCampaigns n/a Update the status of Email Campaigns and schedule emails. Batches of 50 As soon as every 5 minutes
--EmailMarketer emailmarketing Process Email Marketer Rules Daily
--FixedTermTerminations fixedtermterminations Process Fixed Term Terminations Daily
--InvoiceAutoCancellation n/a Automatically cancel old overdue unpaid invoices. 8.10+ Daily
--InvoiceReminders invoicereminders Generate daily reminders for unpaid and overdue invoice Daily
--OverageBilling overagesbilling Process Overage Billing Charges and Generate Invoices Monthly
--ProcessCreditCardPayments ccprocessing Process Credit Card Charges Daily
--ProcessEmailQueue n/a Process scheduled emails within Email Campaigns. Batches of 25 As soon as every 5 minutes
--ServerRemoteMetaData n/a Auto Update Server Meta Data. Displayed on Configuration () > System Settings > Servers or, prior to WHMCS 8.0, Setup > Products/Services > Servers. 7.8+ Hourly
--ServerUsageCount n/a Auto Update Server Usage Count. Displayed on Configuration () > System Settings > Servers or, prior to WHMCS 8.0, Setup > Products/Services > Servers. 7.8+ Hourly
--SslReissues n/a Process MarketConnect SSL certificate reissuances. 8.5+ Daily
--SslSync n/a Check validity of SSL Certificates on services and domains. Batches of 100. 7.7+ Daily
--TenantUsageMetrics n/a Auto Update Service Usage Data. Displayed when viewing Service within Client Area. 7.9+ Twice-daily
--TicketEscalations escalations Process and escalate tickets per any Escalation Rules As soon as every 3 minutes
--UpdateDomainExpiryStatus n/a Update Domain Expiry Status for domains with a past Expiry Date Daily
--UpdateServerUsage usagestats Updating Disk & Bandwidth Usage Stats Daily

Types

There are two types of tasks:

  • Application: Advances state of client data, such as orders, billing, and provisioning
  • System: Provides software related functionality, such as generating backups or performing database normalization.
    • The "DatabaseBackup" task is the only task option of the System type which can be included/excluded from execution. All other System type task options will be performed explicitly as required by WHMCS and thus do not have option flags.

Tasks & --force Option

The "--force" option does exactly that...it will force execute any application tasks (respective of the command [all, skip, do]) regardless if the task is suppose to run once a day, a month, or at a time other than now.

  • The all command with the "--force" flag will execute all application tasks, as if each one were due exactly now.
  • The skip command with the "--force" will first exclude the specified tasks (i.e., the ones provided as task option flags) and then operate on all other tasks as if each were due exactly now, similar to the all command.
  • The do command is designed to only run the tasks specified (i.e., the ones provided as task option flags) and to run them immediately, thus the "--force" option is always implied and is not a valid option.
  • The "--force" option has no effect on System type tasks (except "DatabaseBackup")
  • The "--force" option has no effect on whether the Daily Digest Email Report is sent, that is controlled via the --email-report option.
Passing arguments to PHP scripts requires the register_argc_argv directive to be enabled.

Advanced Task Scheduling

In some environments or use-cases, having fine-grained control of one or more tasks is important. This is possible through a combination of multiple do and skip crontab entries. Tasks performed as part of a do command will not have their internal scheduling tracking modified. This is to ensure the integrity of a normal invocation of the System Cron. If you want a particular task to only execute on a particular schedule, create a do command for that task and alter your main System Cron invocation to skip that task (all other non-itemized tasks will be performed on the WHMCS schedule in this skip). Likewise, if you never wish to have a particular task executed, alter your System Cron entry to be a skip command with the option for that particular task.

Hook Points

The System Cron has six hook events:

  • PreCronJob
    • Fires only during the daily cron run
    • Is invoked before any tasks are executed
    • Registered hooks receive no parameter arguments
  • PreAutomationTask
    • Is invoked before each Application task
    • Registered hooks receive one parameter argument:
      • The task object that is about to be executed, which adheres to WHMCS\Scheduling\Task\TaskInterface
      • The return value of this hook is not inspected. However, if an exception is thrown, the task will not be executed, be marked as incomplete, and iteration to the next task will commence
  • PostAutomationTask
    • Is invoked after each Application task
    • Registered hooks receive two parameter arguments:
      • The task object that was just executed, which adheres to WHMCS\Scheduling\Task\TaskInterface
      • The boolean state if the task executed without throwing an Exception
      • The return value of this hook is not inspected. Any Exception thrown will be discarded
  • DailyCronJobEmail
    • Fires during the daily cron run or when --email-report=1 is specified
    • Is invoked after all Application tasks are executed, immediate prior to the DailyCronJob hook
    • If a registered hook returns true, the digest email report will not be sent
    • Registered hooks receive no parameter arguments
  • DailyCronJob
    • Fires only during the daily cron run
    • Is invoked after all Application tasks are executed, immediate proceeding the DailyCronJobEmail hook
    • Register hooks receive no parameter arguments
  • AfterCronJob
    • Fires each time cron is invoked
    • Is invoked after all Application & System tasks are executed, just prior to script termination
    • Registered hooks receive no parameter arguments

Example Crontab Entries

Below are examples that demonstrate the flexibility of the System Cron input options and how you could craft your crontab entry. For most WHMCS installation, you should just have one entry (Ex. 1). If you wish to disable certain tasks entirely, consider looking at the related functionality's documentation first to understand how your may be able optimize your WHMCS settings from the administration area and potential avoid unnecessary crontab entries.

Ex 1. Standard System Cron entry:

*/5 * * * * php -q /path/to/cron.php

Ex 2. Explicit entry to perform all scheduled task if they are due (will behave the same as Ex. 1):

*/5 * * * * php -q /path/to/cron.php all

Ex 3. Always skip sending domain renewal notices, but perform all other tasks as normal if they are due:

*/5 * * * * php -q /path/to/cron.php skip --DomainRenewalNotices

Ex 4. Always skip ticket escalations and auto suspensions. Process ticket escalations Monday-Friday during business hours, at the top of the hour, and auto suspension Monday-Friday at the start of business:

*/5 * * * * php -q /path/to/cron.php skip --TicketEscalations --AutoSuspensions
0 9,10,11,12,13,14,15,16 * * 1-5 php -q /path/to/cron.php do --TicketEscalations
0 9 * * 1-5 php -q /path/to/cron.php do --AutoSuspensions

Ex 5. In some hosting environments, direct crontab entries are not permitted. The System Cron can be invoked through an HTTP request (provided the script is accessible within the docroot) The follow demonstrates performing all tasks except DomainRenewalNotices and TicketEscalations

GET http://www.example.com/admin/cron.php?command=skip&options=DomainRenewalNotices,TicketEscalations

Legacy Cron File Locations

Prior to WHMCS version 6, the automated task files were located across various directories. From WHMCS version 6 onwards all cron files are now located in the crons directory by default.

To aide in the transition process to their new locations, version 6.0 of WHMCS includes proxy files in the old locations that will allow all existing configured cron and piping commands to continue operating without any changes post-upgrade to 6.0.

However, we encourage you to update your cron and piping commands to use the new locations prior to updating to Version 8.0.

The old locations are deprecated as of Version 6.0, and the proxy functionality is removed as of version 8.0. The proxy files and their proxy locations are:

  • /admin/cron.php
  • /pipe/pipe.php
  • /pipe/pop.php
If you do not require these proxy files, you can safely remove them from your installation.