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

Network Security version1.0 - Module 3.pptx
Network Security version1.0 - Module 3.pptxNetwork Security version1.0 - Module 3.pptx
Network Security version1.0 - Module 3.pptx
Infotainmentforall
 
Software Defined Networking, Concepts and Practical Implementations
Software Defined Networking, Concepts and Practical ImplementationsSoftware Defined Networking, Concepts and Practical Implementations
Software Defined Networking, Concepts and Practical Implementations
Bangladesh Network Operators Group
 
Kolkata @Girls @Call WhatsApp Numbers 🫦0000XX0000🫦 List For Friendship Girls ...
Kolkata @Girls @Call WhatsApp Numbers 🫦0000XX0000🫦 List For Friendship Girls ...Kolkata @Girls @Call WhatsApp Numbers 🫦0000XX0000🫦 List For Friendship Girls ...
Kolkata @Girls @Call WhatsApp Numbers 🫦0000XX0000🫦 List For Friendship Girls ...
paridubey2024#G05
 
Girls Call Shimla 000XX00000 Provide Best And Top Girl Service And No1 in City
Girls Call Shimla 000XX00000 Provide Best And Top Girl Service And No1 in CityGirls Call Shimla 000XX00000 Provide Best And Top Girl Service And No1 in City
Girls Call Shimla 000XX00000 Provide Best And Top Girl Service And No1 in City
dilbaagsingh0898
 
University of California, Riverside diploma
University of California, Riverside diplomaUniversity of California, Riverside diploma
University of California, Riverside diploma
eufdev
 
Chennai Girls Call ServiCe X00XXX00XX Tanisha Best High Class Chennai Available
Chennai Girls Call ServiCe X00XXX00XX Tanisha Best High Class Chennai AvailableChennai Girls Call ServiCe X00XXX00XX Tanisha Best High Class Chennai Available
Chennai Girls Call ServiCe X00XXX00XX Tanisha Best High Class Chennai Available
shamrisumri
 
Portugal Dreamin 24 - How to easily use an API with Flows
Portugal Dreamin 24  - How to easily use an API with FlowsPortugal Dreamin 24  - How to easily use an API with Flows
Portugal Dreamin 24 - How to easily use an API with Flows
Thierry TROUIN ☁
 
Top 50 Data Science Jobs on LinkedIn.docx
Top 50 Data Science Jobs on LinkedIn.docxTop 50 Data Science Jobs on LinkedIn.docx
Top 50 Data Science Jobs on LinkedIn.docx
analyticsinsightmaga
 
Why Your Business Needs a Professional Web Design Company UAE
Why Your Business Needs a Professional Web Design Company UAEWhy Your Business Needs a Professional Web Design Company UAE
Why Your Business Needs a Professional Web Design Company UAE
adelewhite125
 
Career Development Advice for Network Engineers across the Pacific, presented...
Career Development Advice for Network Engineers across the Pacific, presented...Career Development Advice for Network Engineers across the Pacific, presented...
Career Development Advice for Network Engineers across the Pacific, presented...
APNIC
 
Best Skills to Learn for Freelancing.pdf
Best Skills to Learn for Freelancing.pdfBest Skills to Learn for Freelancing.pdf
Best Skills to Learn for Freelancing.pdf
Million-$-Knowledge {Million Dollar Knowledge}
 
Female Service Girls Call Delhi 9873940964 Provide Best And Top Girl Service ...
Female Service Girls Call Delhi 9873940964 Provide Best And Top Girl Service ...Female Service Girls Call Delhi 9873940964 Provide Best And Top Girl Service ...
Female Service Girls Call Delhi 9873940964 Provide Best And Top Girl Service ...
elbertablack
 
Top 50 Telephone Conversation Sample Examples For IT Industries.pdf
Top 50 Telephone Conversation Sample Examples For IT Industries.pdfTop 50 Telephone Conversation Sample Examples For IT Industries.pdf
Top 50 Telephone Conversation Sample Examples For IT Industries.pdf
Krishna L
 
Best CSS Animation Libraries for Web Developers
Best CSS Animation Libraries for Web DevelopersBest CSS Animation Libraries for Web Developers
Best CSS Animation Libraries for Web Developers
Shrestha Raaz
 
IPv6 Deployment Planning and Security Considerations
IPv6 Deployment Planning and Security ConsiderationsIPv6 Deployment Planning and Security Considerations
IPv6 Deployment Planning and Security Considerations
Bangladesh Network Operators Group
 
Ontology for the semantic enhancement, database definition and management and...
Ontology for the semantic enhancement, database definition and management and...Ontology for the semantic enhancement, database definition and management and...
Ontology for the semantic enhancement, database definition and management and...
Edward Blurock
 
Lordsexch ID: An Ultimate Online Cricket ID Provider In India
Lordsexch ID: An Ultimate Online Cricket ID Provider In IndiaLordsexch ID: An Ultimate Online Cricket ID Provider In India
Lordsexch ID: An Ultimate Online Cricket ID Provider In India
exchangeid32
 
Trump Assassination Shirt Trump Assassination Shirt
Trump Assassination Shirt Trump Assassination ShirtTrump Assassination Shirt Trump Assassination Shirt
Trump Assassination Shirt Trump Assassination Shirt
exgf28
 
Effective Tips for Creating the Best Rich Media Ads .pptx
Effective Tips for Creating the Best Rich Media Ads .pptxEffective Tips for Creating the Best Rich Media Ads .pptx
Effective Tips for Creating the Best Rich Media Ads .pptx
AirtoryInc
 
Dewanstudio Project Portfolio 2023 show case
Dewanstudio Project Portfolio 2023 show caseDewanstudio Project Portfolio 2023 show case
Dewanstudio Project Portfolio 2023 show case
DEWANSTUDIO.COM
 

Recently uploaded (20)

Network Security version1.0 - Module 3.pptx
Network Security version1.0 - Module 3.pptxNetwork Security version1.0 - Module 3.pptx
Network Security version1.0 - Module 3.pptx
 
Software Defined Networking, Concepts and Practical Implementations
Software Defined Networking, Concepts and Practical ImplementationsSoftware Defined Networking, Concepts and Practical Implementations
Software Defined Networking, Concepts and Practical Implementations
 
Kolkata @Girls @Call WhatsApp Numbers 🫦0000XX0000🫦 List For Friendship Girls ...
Kolkata @Girls @Call WhatsApp Numbers 🫦0000XX0000🫦 List For Friendship Girls ...Kolkata @Girls @Call WhatsApp Numbers 🫦0000XX0000🫦 List For Friendship Girls ...
Kolkata @Girls @Call WhatsApp Numbers 🫦0000XX0000🫦 List For Friendship Girls ...
 
Girls Call Shimla 000XX00000 Provide Best And Top Girl Service And No1 in City
Girls Call Shimla 000XX00000 Provide Best And Top Girl Service And No1 in CityGirls Call Shimla 000XX00000 Provide Best And Top Girl Service And No1 in City
Girls Call Shimla 000XX00000 Provide Best And Top Girl Service And No1 in City
 
University of California, Riverside diploma
University of California, Riverside diplomaUniversity of California, Riverside diploma
University of California, Riverside diploma
 
Chennai Girls Call ServiCe X00XXX00XX Tanisha Best High Class Chennai Available
Chennai Girls Call ServiCe X00XXX00XX Tanisha Best High Class Chennai AvailableChennai Girls Call ServiCe X00XXX00XX Tanisha Best High Class Chennai Available
Chennai Girls Call ServiCe X00XXX00XX Tanisha Best High Class Chennai Available
 
Portugal Dreamin 24 - How to easily use an API with Flows
Portugal Dreamin 24  - How to easily use an API with FlowsPortugal Dreamin 24  - How to easily use an API with Flows
Portugal Dreamin 24 - How to easily use an API with Flows
 
Top 50 Data Science Jobs on LinkedIn.docx
Top 50 Data Science Jobs on LinkedIn.docxTop 50 Data Science Jobs on LinkedIn.docx
Top 50 Data Science Jobs on LinkedIn.docx
 
Why Your Business Needs a Professional Web Design Company UAE
Why Your Business Needs a Professional Web Design Company UAEWhy Your Business Needs a Professional Web Design Company UAE
Why Your Business Needs a Professional Web Design Company UAE
 
Career Development Advice for Network Engineers across the Pacific, presented...
Career Development Advice for Network Engineers across the Pacific, presented...Career Development Advice for Network Engineers across the Pacific, presented...
Career Development Advice for Network Engineers across the Pacific, presented...
 
Best Skills to Learn for Freelancing.pdf
Best Skills to Learn for Freelancing.pdfBest Skills to Learn for Freelancing.pdf
Best Skills to Learn for Freelancing.pdf
 
Female Service Girls Call Delhi 9873940964 Provide Best And Top Girl Service ...
Female Service Girls Call Delhi 9873940964 Provide Best And Top Girl Service ...Female Service Girls Call Delhi 9873940964 Provide Best And Top Girl Service ...
Female Service Girls Call Delhi 9873940964 Provide Best And Top Girl Service ...
 
Top 50 Telephone Conversation Sample Examples For IT Industries.pdf
Top 50 Telephone Conversation Sample Examples For IT Industries.pdfTop 50 Telephone Conversation Sample Examples For IT Industries.pdf
Top 50 Telephone Conversation Sample Examples For IT Industries.pdf
 
Best CSS Animation Libraries for Web Developers
Best CSS Animation Libraries for Web DevelopersBest CSS Animation Libraries for Web Developers
Best CSS Animation Libraries for Web Developers
 
IPv6 Deployment Planning and Security Considerations
IPv6 Deployment Planning and Security ConsiderationsIPv6 Deployment Planning and Security Considerations
IPv6 Deployment Planning and Security Considerations
 
Ontology for the semantic enhancement, database definition and management and...
Ontology for the semantic enhancement, database definition and management and...Ontology for the semantic enhancement, database definition and management and...
Ontology for the semantic enhancement, database definition and management and...
 
Lordsexch ID: An Ultimate Online Cricket ID Provider In India
Lordsexch ID: An Ultimate Online Cricket ID Provider In IndiaLordsexch ID: An Ultimate Online Cricket ID Provider In India
Lordsexch ID: An Ultimate Online Cricket ID Provider In India
 
Trump Assassination Shirt Trump Assassination Shirt
Trump Assassination Shirt Trump Assassination ShirtTrump Assassination Shirt Trump Assassination Shirt
Trump Assassination Shirt Trump Assassination Shirt
 
Effective Tips for Creating the Best Rich Media Ads .pptx
Effective Tips for Creating the Best Rich Media Ads .pptxEffective Tips for Creating the Best Rich Media Ads .pptx
Effective Tips for Creating the Best Rich Media Ads .pptx
 
Dewanstudio Project Portfolio 2023 show case
Dewanstudio Project Portfolio 2023 show caseDewanstudio Project Portfolio 2023 show case
Dewanstudio Project Portfolio 2023 show case
 

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