SlideShare a Scribd company logo
Time Code: Automating
Tasks in WordPress with
WP-Cron
WordCamp Ottawa
Saturday, May 3, 2014
What is WP-Cron?
!
A task scheduler built into WordPress.
!
Named after the Unix Cron utility:
!
“The software utility cron is a time-based job scheduler in Unix-like
computer operating systems. People who set up and maintain software
environments use cron to schedule jobs (commands or shell scripts) to run
periodically at fixed times, dates, or intervals. It typically automates system
maintenance or administration—though its general-purpose nature makes
it useful for things like connecting to the Internet and downloading email at
regular intervals.[1] The name cron comes from the Greek word for time,
χρόνος chronos.”
!
- Wikipedia
!
!
Scheduling a Single Event
!
The wp_schedule_single_event() function is used to schedule an event to run once.
This could be used, for example, to send a follow up e-mail to a user at a scheduled
time after they register on your site:
!
add_action(‘user_register’, ‘schedule_followup_email’, 10, 1);
!
function schedule_followup_email($user_id) {
	 $userId = get_current_user_id();
	 wp_schedule_event(time() + 3600, ‘event_sendFollowupEmail’, array($user_id));
}
!
function sendWelcomeEmail($user_id) {
	 $user =get_user_by(‘id’, $user_id);
	 wp_mail($user->user_email, ‘Follow Up’, ‘Hope you’ve been enjoying our site’);
}
add_action(‘event_sendFollowupEmail’, ‘sendFollowupEmail’);
!
!
Scheduling Recurring Tasks
!
WP-Cron can run tasks at regular intervals
!
In the core:
!
• Checking if WordPress version is the most current
• Checking for theme and plugin updates
!
Functions:
!
• wp_get_schedule()
• wp_schedule_event()
• wp_get_next_scheduled()
• wp_clear_scheduled_hook()
• wp_unschedule_event()
!
Filter:
!
• cron_schedules
Schedules
Out of the box, WordPress can run recurring tasks:
!
• Daily (once every 24 hours)
• Twice Daily (every 12 hours)
• Hourly (every 60 minutes)
!
You can lookup supported schedules using wp_get_schedules()
!
array (size=3)
'hourly' =>
array (size=2)
'interval' => int 3600
'display' => string 'Once Hourly' (length=11)
'twicedaily' =>
array (size=2)
'interval' => int 43200
'display' => string 'Twice Daily' (length=11)
'daily' =>
array (size=2)
'interval' => int 86400
'display' => string 'Once Daily' (length=10)
Need Another Schedule?
You can create new schedules using the cron_schedules filter.
!
function add_new_cron_intervals($schedules) {
!
	 $schedules[‘weekly’] = array(
	 	 ‘interval’ => 604800,
	 	 ‘display’ => __(‘Once a week’)
	 );
!
	 $schedules[‘fourhours’] = array(
	 	 ‘interval’ => 60 * 60 * 4,
	 	 ‘display’ => __(‘Every four hours’)
	 );
!
	 return $schedules;
!
}
!
add_filter(‘cron_schedules’, ‘add_new_cron_intervals’);
Scheduling Recurring Tasks
!
!
!
function WeeklyMaintenanceTask_activate() {
	 // schedule the task

	 wp_schedule_event(time(), ‘weekly’, ‘WeeklyMaintenanceTask_run’);
}
register_activation_hook( __FILE__, 'WeeklyMaintenanceTask_activate' );
!
!
!
function WeeklyMaintenanceTask_run() {
	 // do maintenance task here
}
add_action(‘WeeklyMaintenanceTask_run’, ‘WeeklyMaintenanceTask_run’);
Cancelling Recurring Tasks
!
!
To clear all events related to a specified hook:
!
function WeeklyMaintenanceTask_deactivate() {
	 // clear scheduled tasks
	 wp_clear_scheduled_hook(‘WeeklyMaintenanceTask_run’);
}
register_deactivation_hook( __FILE__, 'WeeklyMaintenanceTask_deactivate' );
!
!
!
To clear only one event related to a specific hook:
(the difference - you need to know the timestamp of the event)
!
wp_unschedule_event(1399139100, ’WeeklyMaintenanceTask_run’);
Cancelling Recurring Tasks
!
!
When unscheduling/clearing events, the arguments you specified
during scheduling have to match!
!
wp_schedule_event(1399139100, ’MyHook’, array(1000));
!
!
When unscheduling/clearing events, the arguments you specified
during scheduling have to match!
!
wp_unschedule_event(1399139100, ’MyHook’);
Asynchronous Tasks
!
Perfect for long running tasks
!
Allows a user to continue working on your site
!
add_action(‘user_register’, ‘add_user_to_crm’, 10, 1);
!
function add_user_to_crm($user_id) {
	 $userId = get_current_user_id();
	 wp_schedule_event(time(), ‘event_addUserToCRM’, array($user_id));
}
!
function addUserToCRM($user_id) {
	 // insert slow running code here
}
add_action(‘addUserToCRM’, ‘addUserToCRM’);
Looking up a task
!
!
Perfect for avoiding duplicate events
!
wp_next_scheduled( $hook, $args );
!
This function returns the next scheduled cron event for the hook (and arguments)
selected.
!
If found, it will return the timestamp of the next event.
!
If there are no matches, it will return false.
Advantages of WP-Cron
!
!
It will work on all operating systems
!
!
!
!
!
!
!
!
!
No end user configuration required
Disadvantages of WP-Cron
!
Not a true Cron replacement
!
	 Only runs when someone visits your site
!
	 No visits = no jobs
!
!
!
Can use a lot of system resources on a busy site
!
!
Caching can cause events not to fire properly
Disabling WP-Cron
!
!
Add this to your wp-config.php file:
!
define(‘DISABLE_WP_CRON’, true);
Setting up Cron in cPanel
wget -q -O - http://example.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1
Cron GUI by Simon Wheatley
Sample API Integration
Sample API Integration
!
Resources
!
Cron Functions in the WordPress Codex:
http://codex.wordpress.org/Function_Reference/wp_cron
!
Setting up a crontab file on the Unix server:
http://v1.corenominal.org/howto-setup-a-crontab-file/
!
EasyCron Web Service:
https://www.easycron.com/
!
Cron GUI WordPress Plugin:
http://wordpress.org/plugins/cron-view/
!
Epoch & Unix Time Conversion Tools:
http://www.epochconverter.com/
!
These slides:
http://www.5sen.se/wpcron
exit;
!
Thank you!
!
Questions?
!
shawn@fivesense.ca
!
Twitter: @shawnhooper
!
Slides:
http://5sen.se/wpcron
!

More Related Content

What's hot

اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
Mohammad Reza Kamalifard
 
TDD in the wild
TDD in the wildTDD in the wild
TDD in the wild
Brainhub
 
Book integrated assignment
Book integrated assignmentBook integrated assignment
Book integrated assignment
Akash gupta
 
Sequelize
SequelizeSequelize
Sequelize
Tarek Raihan
 
19. CodeIgniter imagini in mysql
19. CodeIgniter imagini in mysql19. CodeIgniter imagini in mysql
19. CodeIgniter imagini in mysql
Razvan Raducanu, PhD
 
Java assgn
Java assgnJava assgn
Java assgn
aa11bb11
 
To infinity and beyond
To infinity and beyondTo infinity and beyond
To infinity and beyond
clintongormley
 
Synchronisation de périphériques avec Javascript et PouchDB
Synchronisation de périphériques avec Javascript et PouchDBSynchronisation de périphériques avec Javascript et PouchDB
Synchronisation de périphériques avec Javascript et PouchDB
Frank Rousseau
 
MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)
MongoSF
 
Hadoop
HadoopHadoop
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Sages
 
Python my SQL - create table
Python my SQL - create tablePython my SQL - create table
Python my SQL - create table
Learnbay Datascience
 
SITCON 雲林定期聚 #1
SITCON 雲林定期聚 #1SITCON 雲林定期聚 #1
SITCON 雲林定期聚 #1
Ting-You Xu
 
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp KrennJavantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Flutter Reactive Programming 介紹 - part 1 (Stream)
Flutter Reactive Programming 介紹 - part 1 (Stream)Flutter Reactive Programming 介紹 - part 1 (Stream)
Flutter Reactive Programming 介紹 - part 1 (Stream)
振揚 陳
 
Django Celery - A distributed task queue
Django Celery - A distributed task queueDjango Celery - A distributed task queue
Django Celery - A distributed task queue
Alex Eftimie
 
Python my sql database connection
Python my sql   database connectionPython my sql   database connection
Python my sql database connection
Learnbay Datascience
 
Montreal User Group - Cloning Cassandra
Montreal User Group - Cloning CassandraMontreal User Group - Cloning Cassandra
Montreal User Group - Cloning Cassandra
Adam Hutson
 
FRP and Bacon.js
FRP and Bacon.jsFRP and Bacon.js
FRP and Bacon.js
Starbuildr
 
Php database connectivity
Php database connectivityPhp database connectivity

What's hot (20)

اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه چهارم کلاس پایتون برای هکرهای قانونی
 
TDD in the wild
TDD in the wildTDD in the wild
TDD in the wild
 
Book integrated assignment
Book integrated assignmentBook integrated assignment
Book integrated assignment
 
Sequelize
SequelizeSequelize
Sequelize
 
19. CodeIgniter imagini in mysql
19. CodeIgniter imagini in mysql19. CodeIgniter imagini in mysql
19. CodeIgniter imagini in mysql
 
Java assgn
Java assgnJava assgn
Java assgn
 
To infinity and beyond
To infinity and beyondTo infinity and beyond
To infinity and beyond
 
Synchronisation de périphériques avec Javascript et PouchDB
Synchronisation de périphériques avec Javascript et PouchDBSynchronisation de périphériques avec Javascript et PouchDB
Synchronisation de périphériques avec Javascript et PouchDB
 
MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)MongoDB Replication (Dwight Merriman)
MongoDB Replication (Dwight Merriman)
 
Hadoop
HadoopHadoop
Hadoop
 
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash courseCodepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
Codepot - Pig i Hive: szybkie wprowadzenie / Pig and Hive crash course
 
Python my SQL - create table
Python my SQL - create tablePython my SQL - create table
Python my SQL - create table
 
SITCON 雲林定期聚 #1
SITCON 雲林定期聚 #1SITCON 雲林定期聚 #1
SITCON 雲林定期聚 #1
 
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp KrennJavantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
 
Flutter Reactive Programming 介紹 - part 1 (Stream)
Flutter Reactive Programming 介紹 - part 1 (Stream)Flutter Reactive Programming 介紹 - part 1 (Stream)
Flutter Reactive Programming 介紹 - part 1 (Stream)
 
Django Celery - A distributed task queue
Django Celery - A distributed task queueDjango Celery - A distributed task queue
Django Celery - A distributed task queue
 
Python my sql database connection
Python my sql   database connectionPython my sql   database connection
Python my sql database connection
 
Montreal User Group - Cloning Cassandra
Montreal User Group - Cloning CassandraMontreal User Group - Cloning Cassandra
Montreal User Group - Cloning Cassandra
 
FRP and Bacon.js
FRP and Bacon.jsFRP and Bacon.js
FRP and Bacon.js
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 

Similar to Time Code: Automating Tasks in WordPress with WP-Cron

Wrangling WP_Cron - WordCamp Grand Rapids 2014
Wrangling WP_Cron - WordCamp Grand Rapids 2014Wrangling WP_Cron - WordCamp Grand Rapids 2014
Wrangling WP_Cron - WordCamp Grand Rapids 2014
cklosowski
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
MongoDB
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
ArthyR3
 
Automating your plugin with WP-Cron
Automating your plugin with WP-CronAutomating your plugin with WP-Cron
Automating your plugin with WP-Cron
Dan Cannon
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
Gianluca Carucci
 
02 Introduction to Javascript
02 Introduction to Javascript02 Introduction to Javascript
02 Introduction to Javascript
crgwbr
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
cacois
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
Gaurav Behere
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
Christoffer Noring
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
Celery
CeleryCelery
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
TechWell
 
Flux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul DixFlux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul Dix
InfluxData
 
Celery with python
Celery with pythonCelery with python
Celery with python
Alexandre González Rodríguez
 
Cloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload CourseCloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload Course
cloudbase.io
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
Lindsay Holmwood
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
Vadym Khondar
 

Similar to Time Code: Automating Tasks in WordPress with WP-Cron (20)

Wrangling WP_Cron - WordCamp Grand Rapids 2014
Wrangling WP_Cron - WordCamp Grand Rapids 2014Wrangling WP_Cron - WordCamp Grand Rapids 2014
Wrangling WP_Cron - WordCamp Grand Rapids 2014
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
 
Automating your plugin with WP-Cron
Automating your plugin with WP-CronAutomating your plugin with WP-Cron
Automating your plugin with WP-Cron
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
02 Introduction to Javascript
02 Introduction to Javascript02 Introduction to Javascript
02 Introduction to Javascript
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Celery
CeleryCelery
Celery
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
Flux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul DixFlux and InfluxDB 2.0 by Paul Dix
Flux and InfluxDB 2.0 by Paul Dix
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Cloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload CourseCloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload Course
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
 

More from Shawn Hooper

Introduction to WordPress Security
Introduction to WordPress SecurityIntroduction to WordPress Security
Introduction to WordPress Security
Shawn Hooper
 
WP REST API: Actionable.co
WP REST API: Actionable.coWP REST API: Actionable.co
WP REST API: Actionable.co
Shawn Hooper
 
Database Considerations for SaaS Products
Database Considerations for SaaS ProductsDatabase Considerations for SaaS Products
Database Considerations for SaaS Products
Shawn Hooper
 
Payments Made Easy with Stripe
Payments Made Easy with StripePayments Made Easy with Stripe
Payments Made Easy with Stripe
Shawn Hooper
 
WordPress Coding Standards & Best Practices
WordPress Coding Standards & Best PracticesWordPress Coding Standards & Best Practices
WordPress Coding Standards & Best Practices
Shawn Hooper
 
Save Time By Manging WordPress from the Command Line
Save Time By Manging WordPress from the Command LineSave Time By Manging WordPress from the Command Line
Save Time By Manging WordPress from the Command Line
Shawn Hooper
 
Writing Clean, Standards Compliant, Testable Code for WordPress
Writing Clean, Standards Compliant, Testable Code for WordPressWriting Clean, Standards Compliant, Testable Code for WordPress
Writing Clean, Standards Compliant, Testable Code for WordPress
Shawn Hooper
 
Creating Multilingual WordPress Websites
Creating Multilingual WordPress WebsitesCreating Multilingual WordPress Websites
Creating Multilingual WordPress Websites
Shawn Hooper
 
Creating Multilingual WordPress Websites
Creating Multilingual WordPress WebsitesCreating Multilingual WordPress Websites
Creating Multilingual WordPress Websites
Shawn Hooper
 
WP-CLI Presentation from WordCamp NYC 2015
WP-CLI Presentation from WordCamp NYC 2015WP-CLI Presentation from WordCamp NYC 2015
WP-CLI Presentation from WordCamp NYC 2015
Shawn Hooper
 
Securing WordPress
Securing WordPressSecuring WordPress
Securing WordPress
Shawn Hooper
 
Writing Secure Code for WordPress
Writing Secure Code for WordPressWriting Secure Code for WordPress
Writing Secure Code for WordPress
Shawn Hooper
 
Manage WordPress From the Command Line with WP-CLI
Manage WordPress From the Command Line with WP-CLIManage WordPress From the Command Line with WP-CLI
Manage WordPress From the Command Line with WP-CLI
Shawn Hooper
 
Hooked on WordPress: WordCamp Columbus
Hooked on WordPress: WordCamp ColumbusHooked on WordPress: WordCamp Columbus
Hooked on WordPress: WordCamp Columbus
Shawn Hooper
 
WP-CLI Talk from WordCamp Montreal
WP-CLI Talk from WordCamp MontrealWP-CLI Talk from WordCamp Montreal
WP-CLI Talk from WordCamp Montreal
Shawn Hooper
 
WP-CLI - WordCamp Miami 2015
WP-CLI - WordCamp Miami 2015WP-CLI - WordCamp Miami 2015
WP-CLI - WordCamp Miami 2015
Shawn Hooper
 
Save Time by Managing WordPress from the Command Line
Save Time by Managing WordPress from the Command LineSave Time by Managing WordPress from the Command Line
Save Time by Managing WordPress from the Command Line
Shawn Hooper
 

More from Shawn Hooper (17)

Introduction to WordPress Security
Introduction to WordPress SecurityIntroduction to WordPress Security
Introduction to WordPress Security
 
WP REST API: Actionable.co
WP REST API: Actionable.coWP REST API: Actionable.co
WP REST API: Actionable.co
 
Database Considerations for SaaS Products
Database Considerations for SaaS ProductsDatabase Considerations for SaaS Products
Database Considerations for SaaS Products
 
Payments Made Easy with Stripe
Payments Made Easy with StripePayments Made Easy with Stripe
Payments Made Easy with Stripe
 
WordPress Coding Standards & Best Practices
WordPress Coding Standards & Best PracticesWordPress Coding Standards & Best Practices
WordPress Coding Standards & Best Practices
 
Save Time By Manging WordPress from the Command Line
Save Time By Manging WordPress from the Command LineSave Time By Manging WordPress from the Command Line
Save Time By Manging WordPress from the Command Line
 
Writing Clean, Standards Compliant, Testable Code for WordPress
Writing Clean, Standards Compliant, Testable Code for WordPressWriting Clean, Standards Compliant, Testable Code for WordPress
Writing Clean, Standards Compliant, Testable Code for WordPress
 
Creating Multilingual WordPress Websites
Creating Multilingual WordPress WebsitesCreating Multilingual WordPress Websites
Creating Multilingual WordPress Websites
 
Creating Multilingual WordPress Websites
Creating Multilingual WordPress WebsitesCreating Multilingual WordPress Websites
Creating Multilingual WordPress Websites
 
WP-CLI Presentation from WordCamp NYC 2015
WP-CLI Presentation from WordCamp NYC 2015WP-CLI Presentation from WordCamp NYC 2015
WP-CLI Presentation from WordCamp NYC 2015
 
Securing WordPress
Securing WordPressSecuring WordPress
Securing WordPress
 
Writing Secure Code for WordPress
Writing Secure Code for WordPressWriting Secure Code for WordPress
Writing Secure Code for WordPress
 
Manage WordPress From the Command Line with WP-CLI
Manage WordPress From the Command Line with WP-CLIManage WordPress From the Command Line with WP-CLI
Manage WordPress From the Command Line with WP-CLI
 
Hooked on WordPress: WordCamp Columbus
Hooked on WordPress: WordCamp ColumbusHooked on WordPress: WordCamp Columbus
Hooked on WordPress: WordCamp Columbus
 
WP-CLI Talk from WordCamp Montreal
WP-CLI Talk from WordCamp MontrealWP-CLI Talk from WordCamp Montreal
WP-CLI Talk from WordCamp Montreal
 
WP-CLI - WordCamp Miami 2015
WP-CLI - WordCamp Miami 2015WP-CLI - WordCamp Miami 2015
WP-CLI - WordCamp Miami 2015
 
Save Time by Managing WordPress from the Command Line
Save Time by Managing WordPress from the Command LineSave Time by Managing WordPress from the Command Line
Save Time by Managing WordPress from the Command Line
 

Recently uploaded

怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
rtunex8r
 
Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?
Paul Walk
 
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
xjq03c34
 
Bengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal BrandingBengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal Branding
Tarandeep Singh
 
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
3a0sd7z3
 
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
3a0sd7z3
 
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
k4ncd0z
 
Discover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to IndiaDiscover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to India
davidjhones387
 
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
APNIC
 
HijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process HollowingHijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process Hollowing
Donato Onofri
 
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
APNIC
 
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
thezot
 

Recently uploaded (12)

怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
怎么办理(umiami毕业证书)美国迈阿密大学毕业证文凭证书实拍图原版一模一样
 
Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?Should Repositories Participate in the Fediverse?
Should Repositories Participate in the Fediverse?
 
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
办理新西兰奥克兰大学毕业证学位证书范本原版一模一样
 
Bengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal BrandingBengaluru Dreamin' 24 - Personal Branding
Bengaluru Dreamin' 24 - Personal Branding
 
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
快速办理(Vic毕业证书)惠灵顿维多利亚大学毕业证完成信一模一样
 
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
快速办理(新加坡SMU毕业证书)新加坡管理大学毕业证文凭证书一模一样
 
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理一比一原版(USYD毕业证)悉尼大学毕业证如何办理
一比一原版(USYD毕业证)悉尼大学毕业证如何办理
 
Discover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to IndiaDiscover the benefits of outsourcing SEO to India
Discover the benefits of outsourcing SEO to India
 
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
 
HijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process HollowingHijackLoader Evolution: Interactive Process Hollowing
HijackLoader Evolution: Interactive Process Hollowing
 
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
 
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
 

Time Code: Automating Tasks in WordPress with WP-Cron

  • 1. Time Code: Automating Tasks in WordPress with WP-Cron WordCamp Ottawa Saturday, May 3, 2014
  • 2. What is WP-Cron? ! A task scheduler built into WordPress. ! Named after the Unix Cron utility: ! “The software utility cron is a time-based job scheduler in Unix-like computer operating systems. People who set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. It typically automates system maintenance or administration—though its general-purpose nature makes it useful for things like connecting to the Internet and downloading email at regular intervals.[1] The name cron comes from the Greek word for time, χρόνος chronos.” ! - Wikipedia ! !
  • 3. Scheduling a Single Event ! The wp_schedule_single_event() function is used to schedule an event to run once. This could be used, for example, to send a follow up e-mail to a user at a scheduled time after they register on your site: ! add_action(‘user_register’, ‘schedule_followup_email’, 10, 1); ! function schedule_followup_email($user_id) { $userId = get_current_user_id(); wp_schedule_event(time() + 3600, ‘event_sendFollowupEmail’, array($user_id)); } ! function sendWelcomeEmail($user_id) { $user =get_user_by(‘id’, $user_id); wp_mail($user->user_email, ‘Follow Up’, ‘Hope you’ve been enjoying our site’); } add_action(‘event_sendFollowupEmail’, ‘sendFollowupEmail’); ! !
  • 4. Scheduling Recurring Tasks ! WP-Cron can run tasks at regular intervals ! In the core: ! • Checking if WordPress version is the most current • Checking for theme and plugin updates ! Functions: ! • wp_get_schedule() • wp_schedule_event() • wp_get_next_scheduled() • wp_clear_scheduled_hook() • wp_unschedule_event() ! Filter: ! • cron_schedules
  • 5. Schedules Out of the box, WordPress can run recurring tasks: ! • Daily (once every 24 hours) • Twice Daily (every 12 hours) • Hourly (every 60 minutes) ! You can lookup supported schedules using wp_get_schedules() ! array (size=3) 'hourly' => array (size=2) 'interval' => int 3600 'display' => string 'Once Hourly' (length=11) 'twicedaily' => array (size=2) 'interval' => int 43200 'display' => string 'Twice Daily' (length=11) 'daily' => array (size=2) 'interval' => int 86400 'display' => string 'Once Daily' (length=10)
  • 6. Need Another Schedule? You can create new schedules using the cron_schedules filter. ! function add_new_cron_intervals($schedules) { ! $schedules[‘weekly’] = array( ‘interval’ => 604800, ‘display’ => __(‘Once a week’) ); ! $schedules[‘fourhours’] = array( ‘interval’ => 60 * 60 * 4, ‘display’ => __(‘Every four hours’) ); ! return $schedules; ! } ! add_filter(‘cron_schedules’, ‘add_new_cron_intervals’);
  • 7. Scheduling Recurring Tasks ! ! ! function WeeklyMaintenanceTask_activate() { // schedule the task
 wp_schedule_event(time(), ‘weekly’, ‘WeeklyMaintenanceTask_run’); } register_activation_hook( __FILE__, 'WeeklyMaintenanceTask_activate' ); ! ! ! function WeeklyMaintenanceTask_run() { // do maintenance task here } add_action(‘WeeklyMaintenanceTask_run’, ‘WeeklyMaintenanceTask_run’);
  • 8. Cancelling Recurring Tasks ! ! To clear all events related to a specified hook: ! function WeeklyMaintenanceTask_deactivate() { // clear scheduled tasks wp_clear_scheduled_hook(‘WeeklyMaintenanceTask_run’); } register_deactivation_hook( __FILE__, 'WeeklyMaintenanceTask_deactivate' ); ! ! ! To clear only one event related to a specific hook: (the difference - you need to know the timestamp of the event) ! wp_unschedule_event(1399139100, ’WeeklyMaintenanceTask_run’);
  • 9. Cancelling Recurring Tasks ! ! When unscheduling/clearing events, the arguments you specified during scheduling have to match! ! wp_schedule_event(1399139100, ’MyHook’, array(1000)); ! ! When unscheduling/clearing events, the arguments you specified during scheduling have to match! ! wp_unschedule_event(1399139100, ’MyHook’);
  • 10. Asynchronous Tasks ! Perfect for long running tasks ! Allows a user to continue working on your site ! add_action(‘user_register’, ‘add_user_to_crm’, 10, 1); ! function add_user_to_crm($user_id) { $userId = get_current_user_id(); wp_schedule_event(time(), ‘event_addUserToCRM’, array($user_id)); } ! function addUserToCRM($user_id) { // insert slow running code here } add_action(‘addUserToCRM’, ‘addUserToCRM’);
  • 11. Looking up a task ! ! Perfect for avoiding duplicate events ! wp_next_scheduled( $hook, $args ); ! This function returns the next scheduled cron event for the hook (and arguments) selected. ! If found, it will return the timestamp of the next event. ! If there are no matches, it will return false.
  • 12. Advantages of WP-Cron ! ! It will work on all operating systems ! ! ! ! ! ! ! ! ! No end user configuration required
  • 13. Disadvantages of WP-Cron ! Not a true Cron replacement ! Only runs when someone visits your site ! No visits = no jobs ! ! ! Can use a lot of system resources on a busy site ! ! Caching can cause events not to fire properly
  • 14. Disabling WP-Cron ! ! Add this to your wp-config.php file: ! define(‘DISABLE_WP_CRON’, true);
  • 15. Setting up Cron in cPanel wget -q -O - http://example.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1
  • 16. Cron GUI by Simon Wheatley
  • 19. Resources ! Cron Functions in the WordPress Codex: http://codex.wordpress.org/Function_Reference/wp_cron ! Setting up a crontab file on the Unix server: http://v1.corenominal.org/howto-setup-a-crontab-file/ ! EasyCron Web Service: https://www.easycron.com/ ! Cron GUI WordPress Plugin: http://wordpress.org/plugins/cron-view/ ! Epoch & Unix Time Conversion Tools: http://www.epochconverter.com/ ! These slides: http://www.5sen.se/wpcron