Remove Action Scheduler development files

This commit is contained in:
Brent Shepherd 2019-03-28 15:33:41 +10:00
parent fbfd91f6b9
commit f450c8d92a
48 changed files with 0 additions and 5739 deletions

View File

@ -1,9 +0,0 @@
docs export-ignore
tests export-ignore
codecov.yml export-ignore
.github export-ignore
.travis.yml export-ignore
.gitattributes export-ignore
.gitignore export-ignore
phpunit.xml.dist export-ignore

View File

@ -1,15 +0,0 @@
template: |
## next release – date
<!-- Move the individual changes below into the appropriate section -->
$CHANGES
**Added**
**Changed**
**Deprecated**
**Removed**
**Fixed**
**Security**
change-template: '* $TITLE (PR #$NUMBER)'

View File

@ -1,3 +0,0 @@
phpunit.xml
vendor
.idea

View File

@ -1,37 +0,0 @@
# Travis CI Configuration File
# Tell Travis CI we're using PHP
language: php
# We nee to use Precise, not Trusty, to test against PHP 5.3, see https://github.com/travis-ci/travis-ci/issues/8219
dist: precise
# Versions of PHP to test against
php:
- "5.3"
- "5.4"
- "5.5"
- "5.6"
- "7.0"
- "7.1"
# Specify versions of WordPress to test against
# WP_VERSION = WordPress version number (use "master" for SVN trunk)
# WP_MULTISITE = whether to test multisite (use either "0" or "1")
env:
- WP_VERSION=4.8 WP_MULTISITE=0
- WP_VERSION=4.7 WP_MULTISITE=0
- WP_VERSION=4.6 WP_MULTISITE=0
- WP_VERSION=4.8 WP_MULTISITE=1
- WP_VERSION=4.7 WP_MULTISITE=1
- WP_VERSION=4.6 WP_MULTISITE=1
# Grab the setup script and execute
before_script:
- source tests/travis/setup.sh $TRAVIS_PHP_VERSION
script:
- if [[ "$TRAVIS_PHP_VERSION" == "7.1" ]] && [[ "$WP_VERSION" == "4.8" ]] && [[ "$WP_MULTISITE" == "0" ]] && [[ "$TRAVIS_BRANCH" == "master" ]]; then phpunit --configuration tests/phpunit.xml.dist --coverage-clover clover.xml; else phpunit --configuration tests/phpunit.xml.dist; fi
after_script:
- bash <(curl -s https://codecov.io/bash)

View File

@ -1,13 +0,0 @@
codecov:
branch: master
coverage:
ignore:
- tests/.*
- lib/.*
status:
project: false
patch: false
changes: false
comment: false

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@
actionscheduler.org

View File

@ -1,7 +0,0 @@
title: Action Scheduler - Job Queue for WordPress
description: A scalable, traceable job queue for background processing large queues of tasks in WordPress. Designed for distribution in WordPress plugins - no server access required.
theme: jekyll-theme-hacker
permalink: /:slug/
plugins:
- jekyll-seo-tag
- jekyll-sitemap

View File

@ -1,62 +0,0 @@
<!DOCTYPE html>
<html lang="{{ site.lang | default: "en-US" }}">
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{ '/assets/css/style.css?v=' | append: site.github.build_revision | relative_url }}">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#63c0f5">
<meta name="msapplication-TileColor" content="#151515">
<meta name="theme-color" content="#ffffff">
{% seo %}
</head>
<body>
<header>
<a class="github-corner" href="https://github.com/Prospress/action-scheduler/" aria-label="View on GitHub">
<svg width="80" height="80" viewBox="0 0 250 250" style="fill:#b5e853; color:#151513; position: fixed; top: 0; border: 0; right: 0;" aria-hidden="true">
<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path>
</svg>
</a>
<div class="container">
<p><a href="/usage/">Usage</a> | <a href="/admin/">Admin</a> | <a href="/wp-cli/">WP-CLI</a> | <a href="/perf/">Background Processing at Scale</a> | <a href="/api/">API</a> | <a href="/faq/">FAQ</a>
<h1><a href="/">action-scheduler</a></h1>
<h2>A scalable, traceable job queue for background processing large queues of tasks in WordPress. Designed for distribution in WordPress plugins - no server access required.</h2>
</div>
</header>
<div class="container">
<section id="main_content">
{{ content }}
</section>
</div>
<footer>
<div class="container">
<p><a href="/usage/">Usage</a> | <a href="/admin/">Admin</a> | <a href="/wp-cli/">WP-CLI</a> | <a href="/perf/">Background Processing at Scale</a> | <a href="/api/">API</a> | <a href="/faq/">FAQ</a>
<p class="footer-image">
<a href="https://prospress.com"><img src="http://pic.pros.pr/eb8dcec9bd54/prospress-hacker-green-logo.png" width="120"></a>
</p>
</div>
</footer>
{% if site.google_analytics %}
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '{{ site.google_analytics }}', 'auto');
ga('send', 'pageview');
</script>
{% endif %}
</body>
</html>

View File

@ -1,22 +0,0 @@
---
description: Learn how to administer background jobs with the Action Scheduler job queue for WordPress.
---
# Scheduled Actions Administration Screen
Action Scheduler has a built in administration screen for monitoring, debugging and manually triggering scheduled actions.
The administration interface is accesible through both:
1. **Tools > Scheduled Actions**
1. **WooCommerce > Status > Scheduled Actions**, when WooCommerce is installed.
Among other tasks, from the admin screen you can:
* run a pending action
* view the scheduled actions with a specific status, like the all actions which have failed or are in-progress (https://cldup.com/NNTwE88Xl8.png).
* view the log entries for a specific action to find out why it failed.
* sort scheduled actions by hook name, scheduled date, claim ID or group name.
Still have questions? Check out the [FAQ](/faq).
![](https://cldup.com/5BA2BNB1sw.png)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

View File

@ -1,179 +0,0 @@
---
description: Reference guide for background processing functions provided by the Action Scheduler job queue for WordPress.
---
# API Reference
Action Scheduler provides a range of functions for scheduling hooks to run at some time in the future on one or more occassions.
To understand the scheduling functoins, it can help to think of them as extensions to WordPress' `do_action()` function that add the ability to delay and repeat when the hook will be triggered.
## WP-Cron APIs vs. Action Scheduler APIs
The Action Scheduler API functions are designed to mirror the WordPress [WP-Cron API functions](http://codex.wordpress.org/Category:WP-Cron_Functions).
Functions return similar values and accept similar arguments to their WP-Cron counterparts. The notable differences are:
* `as_schedule_single_action()` & `as_schedule_recurring_action()` will return the post ID of the scheduled action rather than boolean indicating whether the event was scheduled
* `as_schedule_recurring_action()` takes an interval in seconds as the recurring interval rather than an arbitrary string
* `as_schedule_single_action()` & `as_schedule_recurring_action()` can accept a `$group` parameter to group different actions for the one plugin together.
* the `wp_` prefix is substituted with `as_` and the term `event` is replaced with `action`
## API Function Availability
As mentioned in the [Usage - Load Order](/usage/#load-order) section, Action Scheduler will initialize itself on the `'init'` hook with priority `1`. While API functions are loaded prior to this and call be called, they should not be called until after `'init'` with priority `1`, because each component, like the data store, has not yet been initialized.
Do not use Action Scheduler API functions prior to `'init'` hook with priority `1`. Doing so could lead to unexpected results, like data being stored in the incorrect location.
## Function Reference / `as_schedule_single_action()`
### Description
Schedule an action to run one time.
### Usage
```php
as_schedule_single_action( $timestamp, $hook, $args, $group )
````
### Parameters
- **$timestamp** (integer)(required) The Unix timestamp representing the date you want the action to run. Default: _none_.
- **$hook** (string)(required) Name of the action hook. Default: _none_.
- **$args** (array) Arguments to pass to callbacks when the hook triggers. Default: _`array()`_.
- **$group** (array) The group to assign this job to. Default: _''_.
### Return value
(integer) the action's ID in the [posts](http://codex.wordpress.org/Database_Description#Table_Overview) table.
## Function Reference / `as_schedule_recurring_action()`
### Description
Schedule an action to run repeatedly with a specified interval in seconds.
### Usage
```php
as_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args, $group )
````
### Parameters
- **$timestamp** (integer)(required) The Unix timestamp representing the date you want the action to run. Default: _none_.
- **$interval_in_seconds** (integer)(required) How long to wait between runs. Default: _none_.
- **$hook** (string)(required) Name of the action hook. Default: _none_.
- **$args** (array) Arguments to pass to callbacks when the hook triggers. Default: _`array()`_.
- **$group** (array) The group to assign this job to. Default: _''_.
### Return value
(integer) the action's ID in the [posts](http://codex.wordpress.org/Database_Description#Table_Overview) table.
## Function Reference / `as_schedule_cron_action()`
### Description
Schedule an action that recurs on a cron-like schedule.
### Usage
```php
as_schedule_cron_action( $timestamp, $schedule, $hook, $args, $group )
````
### Parameters
- **$timestamp** (integer)(required) The Unix timestamp representing the date you want the action to run. Default: _none_.
- **$schedule** (string)(required) $schedule A cron-link schedule string, see http://en.wikipedia.org/wiki/Cron. Default: _none_.
- **$hook** (string)(required) Name of the action hook. Default: _none_.
- **$args** (array) Arguments to pass to callbacks when the hook triggers. Default: _`array()`_.
- **$group** (array) The group to assign this job to. Default: _''_.
### Return value
(integer) the action's ID in the [posts](http://codex.wordpress.org/Database_Description#Table_Overview) table.
## Function Reference / `as_unschedule_action()`
### Description
Cancel the next occurrence of a job.
### Usage
```php
as_unschedule_action( $hook, $args, $group )
````
### Parameters
- **$hook** (string)(required) Name of the action hook. Default: _none_.
- **$args** (array) Arguments to pass to callbacks when the hook triggers. Default: _`array()`_.
- **$group** (array) The group to assign this job to. Default: _''_.
### Return value
(null)
## Function Reference / `as_next_scheduled_action()`
### Description
Returns the next timestamp for a scheduled action.
### Usage
```php
as_next_scheduled_action( $hook, $args, $group )
````
### Parameters
- **$hook** (string)(required) Name of the action hook. Default: _none_.
- **$args** (array) Arguments to pass to callbacks when the hook triggers. Default: _`array()`_.
- **$group** (array) The group to assign this job to. Default: _''_.
### Return value
(integer|boolean) The timestamp for the next occurrence, or false if nothing was found.
## Function Reference / `as_get_scheduled_actions()`
### Description
Find scheduled actions.
### Usage
```php
as_get_scheduled_actions( $args, $return_format )
````
### Parameters
- **$args** (array) Arguments to search and filter results by. Possible arguments, with their default values:
* `'hook' => ''` - the name of the action that will be triggered
* `'args' => NULL` - the args array that will be passed with the action
* `'date' => NULL` - the scheduled date of the action. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime().
* `'date_compare' => '<=`' - operator for testing "date". accepted values are '!=', '>', '>=', '<', '<=', '='
* `'modified' => NULL` - the date the action was last updated. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime().
* `'modified_compare' => '<='` - operator for testing "modified". accepted values are '!=', '>', '>=', '<', '<=', '='
* `'group' => ''` - the group the action belongs to
* `'status' => ''` - ActionScheduler_Store::STATUS_COMPLETE or ActionScheduler_Store::STATUS_PENDING
* `'claimed' => NULL` - TRUE to find claimed actions, FALSE to find unclaimed actions, a string to find a specific claim ID
* `'per_page' => 5` - Number of results to return
* `'offset' => 0`
* `'orderby' => 'date'` - accepted values are 'hook', 'group', 'modified', or 'date'
* `'order' => 'ASC'`
- **$return_format** (string) The format in which to return the scheduled actions: 'OBJECT', 'ARRAY_A', or 'ids'. Default: _'OBJECT'_.
### Return value
(array) Array of the actions matching the criteria specified with `$args`.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.9 KiB

View File

@ -1,57 +0,0 @@
---
---
@import "{{ site.theme }}";
a {
text-shadow: none;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
header h1 a {
color: #b5e853;
}
.container {
max-width: 700px;
}
footer {
margin-top: 6em;
padding: 1.6em 0;
border-top: 1px dashed #b5e853;
}
.footer-image {
text-align: center;
padding-top: 1em;
}
.github-corner:hover .octo-arm {
animation:octocat-wave 560ms ease-in-out
}
@keyframes octocat-wave{
0%,100%{
transform:rotate(0)
}
20%,60%{
transform:rotate(-25deg)
}
40%,80%{
transform:rotate(10deg)
}
}
@media (max-width:500px){
.github-corner:hover .octo-arm {
animation:none
}
.github-corner .octo-arm{
animation:octocat-wave 560ms ease-in-out
}
}

View File

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
<msapplication>
<tile>
<square150x150logo src="/mstile-150x150.png"/>
<TileColor>#151515</TileColor>
</tile>
</msapplication>
</browserconfig>

View File

@ -1,101 +0,0 @@
## FAQ
### Is it safe to release Action Scheduler in my plugin? Won't its functions conflict with another copy of the library?
Action Scheduler is designed to be used and released in plugins. It avoids redeclaring public API functions when more than one copy of the library is being loaded by different plugins. It will also load only the most recent version of itself (by checking registered versions after all plugins are loaded on the `'plugins_loaded'` hook).
To use it in your plugin, simply require the `action-scheduler/action-scheduler.php` file. Action Scheduler will take care of the rest.
### I don't want to use WP-Cron. Does Action Scheduler depend on WP-Cron?
By default, Action Scheduler is initiated by WP-Cron. However, it has no dependency on the WP-Cron system. You can initiate the Action Scheduler queue in other ways with just one or two lines of code.
For example, you can start a queue directly by calling:
```php
ActionScheduler::runner()->run();
```
Or trigger the `'action_scheduler_run_queue'` hook and let Action Scheduler do it for you:
```php
do_action( 'action_scheduler_run_queue' );
```
Further customization can be done by extending the `ActionScheduler_Abstract_QueueRunner` class to create a custom Queue Runner. For an example of a customized queue runner, see the [`ActionScheduler_WPCLI_QueueRunner`](https://github.com/Prospress/action-scheduler/blob/master/classes/ActionScheduler_WPCLI_QueueRunner.php), which is used when running WP CLI.
Want to create some other method for initiating Action Scheduler? [Open a new issue](https://github.com/Prospress/action-scheduler/issues/new), we'd love to help you with it.
### I don't want to use WP-Cron, ever. Does Action Scheduler replace WP-Cron?
By default, Action Scheduler is designed to work alongside WP-Cron and not change any of its behaviour. This helps avoid unexpectedly overriding WP-Cron on sites installing your plugin, which may have nothing to do with WP-Cron.
However, we can understand why you might want to replace WP-Cron completely in environments within you control, especially as it gets you the advantages of Action Scheduler. This should be possible without too much code.
You could use the `'schedule_event'` hook in WordPress to use Action Scheduler for only newly scheduled WP-Cron jobs and map the `$event` param to Action Scheduler API functions.
Alternatively, you can use a combination of the `'pre_update_option_cron'` and `'pre_option_cron'` hooks to override all new and previously scheduled WP-Cron jobs (similar to the way [Cavalcade](https://github.com/humanmade/Cavalcade) does it).
If you'd like to create a plugin to do this automatically and want to share your work with others, [open a new issue to let us know](https://github.com/Prospress/action-scheduler/issues/new), we'd love to help you with it.
### Eww gross, Custom Post Types! That's _so_ 2010. Can I use a different storage scheme?
Of course! Action Scheduler data storage is completely swappable, and always has been.
You can store scheduled actions in custom tables in the WordPress site's database. Some sites using it already are. You can actually store them anywhere for that matter, like in a remote storage service from Amazon Web Services.
To implement a custom store:
1. extend the abstract `ActionScheduler_Store` class, being careful to implement each of its methods
2. attach a callback to `'action_scheduler_store_class'` to tell Action Scheduler your class is the one which should be used to manage storage, e.g.
```
function eg_define_custom_store( $existing_storage_class ) {
return 'My_Radical_Action_Scheduler_Store';
}
add_filter( 'action_scheduler_store_class', 'eg_define_custom_store', 10, 1 );
```
Take a look at the `ActionScheduler_wpPostStore` class for an example implementation of `ActionScheduler_Store`.
If you'd like to create a plugin to do this automatically and release it publicly to help others, [open a new issue to let us know](https://github.com/Prospress/action-scheduler/issues/new), we'd love to help you with it.
> Note: we're also moving Action Scheduler itself to use [custom tables for better scalability](https://github.com/Prospress/action-scheduler/issues/77).
### Can I use a different storage scheme just for logging?
Of course! Action Scheduler's logger is completely swappable, and always has been. You can also customise where logs are stored, and the storage mechanism.
To implement a custom logger:
1. extend the abstract `ActionScheduler_Logger` class, being careful to implement each of its methods
2. attach a callback to `'action_scheduler_logger_class'` to tell Action Scheduler your class is the one which should be used to manage logging, e.g.
```
function eg_define_custom_logger( $existing_storage_class ) {
return 'My_Radical_Action_Scheduler_Logger';
}
add_filter( 'action_scheduler_logger_class', 'eg_define_custom_logger', 10, 1 );
```
Take a look at the `ActionScheduler_wpCommentLogger` class for an example implementation of `ActionScheduler_Logger`.
### I want to run Action Scheduler only on a dedicated application server in my cluster. Can I do that?
Wow, now you're really asking the tough questions. In theory, yes, this is possible. The `ActionScheduler_QueueRunner` class, which is responsible for running queues, is swappable via the `'action_scheduler_queue_runner_class'` filter.
Because of this, you can effectively customise queue running however you need. Whether that means tweaking minor things, like not using WP-Cron at all to initiate queues by overriding `ActionScheduler_QueueRunner::init()`, or completely changing how and where queues are run, by overriding `ActionScheduler_QueueRunner::run()`.
### Is Action Scheduler safe to use on my production site?
Yes, absolutely! Action Scheduler is actively used on tens of thousands of production sites already. Right now it's responsible for scheduling everything from emails to payments.
In fact, every month, Action Scheduler processes millions of payments as part of the [WooCommerce Subscriptions](https://woocommerce.com/products/woocommerce-subscriptions/) extension.
It requires no setup, and won't override any WordPress APIs (unless you want it to).
### How does Action Scheduler work on WordPress Multisite?
Action Scheduler is designed to manage the scheduled actions on a single site. It has no special handling for running queues across multiple sites in a multisite network. That said, because it's storage and Queue Runner are completely swappable, it would be possible to write multisite handling classes to use with it.
If you'd like to create a multisite plugin to do this and release it publicly to help others, [open a new issue to let us know](https://github.com/Prospress/action-scheduler/issues/new), we'd love to help you with it.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

View File

@ -1 +0,0 @@
google-site-verification: google14ef723abb376cd3.html

View File

@ -1,68 +0,0 @@
---
title: Action Scheduler - Background Processing Job Queue for WordPress
---
## WordPress Job Queue with Background Processing
Action Scheduler is a library for triggering a WordPress hook to run at some time in the future. Each hook can be scheduled with unique data, to allow callbacks to perform operations on that data. The hook can also be scheduled to run on one or more occassions.
Think of it like an extension to `do_action()` which adds the ability to delay and repeat a hook.
It just so happens, this functionality also creates a robust job queue for background processing large queues of tasks in WordPress. With the additional of logging and an [administration interface](/admin/), that also provide tracability on your tasks processed in the background.
### Battle-Tested Background Processing
Every month, Action Scheduler processes millions of payments for [Subscriptions](https://woocommerce.com/products/woocommerce-subscriptions/), webhooks for [WooCommerce](https://wordpress.org/plugins/woocommerce/), as well as emails and other events for a range of other plugins.
It's been seen on live sites processing queues in excess of 50,000 jobs and doing resource intensive operations, like processing payments and creating orders, in 10 concurrent queues at a rate of over 10,000 actions / hour without negatively impacting normal site operations.
This is all possible on infrastructure and WordPress sites outside the control of the plugin author.
Action Scheduler is specifically designed for distribution in WordPress plugins (and themes) - no server access required. If your plugin needs background processing, especially of large sets of tasks, Action Scheduler can help.
### How it Works
Action Scheduler uses a WordPress [custom post type](http://codex.wordpress.org/Post_Types), creatively named `scheduled-action`, to store the hook name, arguments and scheduled date for an action that should be triggered at some time in the future.
The scheduler will attempt to run every minute by attaching itself as a callback to the `'action_scheduler_run_schedule'` hook, which is scheduled using WordPress's built-in [WP-Cron](http://codex.wordpress.org/Function_Reference/wp_cron) system.
When triggered, Action Scheduler will check for posts of the `scheduled-action` type that have a `post_date` at or before this point in time i.e. actions scheduled to run now or at sometime in the past.
### Batch Processing Background Jobs
If there are actions to be processed, Action Scheduler will stake a unique claim for a batch of 20 actions and begin processing that batch. The PHP process spawned to run the batch will then continue processing batches of 20 actions until it times out or exhausts available memory.
If your site has a large number of actions scheduled to run at the same time, Action Scheduler will process more than one batch at a time. Specifically, when the `'action_scheduler_run_schedule'` hook is triggered approximately one minute after the first batch began processing, a new PHP process will stake a new claim to a batch of actions which were not claimed by the previous process. It will then begin to process that batch.
This will continue until all actions are processed using a maximum of 5 concurrent queues.
### Housekeeping
Before processing a batch, the scheduler will remove any existing claims on actions which have been sitting in a queue for more than five minutes.
Action Scheduler will also trash any actions which were completed more than a month ago.
If an action runs for more than 5 minutes, Action Scheduler will assume the action has timed out and will mark it as failed. However, if all callbacks attached to the action were to successfully complete sometime after that 5 minute timeout, its status would later be updated to completed.
### Traceable Background Processing
Did your background job run?
Never be left wondering with Action Scheduler's built-in record keeping.
All events for each action are logged in the [comments table](http://codex.wordpress.org/Database_Description#Table_Overview) and displayed in the [administration interface](/admin/).
The events logged by default include when an action:
* is created
* starts
* completes
* fails
If it fails with an error that can be recorded, that error will be recorded in the log and visible in administration interface, making it possible to trace what went wrong at some point in the past on a site you didn't have access to in the past.
Actions can also be grouped together using a custom taxonomy named `action-group`.
## Credits
Developed and maintained by [Prospress](http://prospress.com/) in collaboration with [Flightless](https://flightless.us/).
Collaboration is cool. We'd love to work with you to improve Action Scheduler. [Pull Requests](https://github.com/prospress/action-scheduler/pulls) welcome.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

View File

@ -1,127 +0,0 @@
---
title: WordPress Background Processing at Scale - Action Scheduler Job Queue
description: Learn how to do WordPress background processing at scale by tuning the Action Scheduler job queue's default WP Cron runner.
---
# Background Processing at Scale
Action Scheduler's default processing is designed to work reliably across all different hosting environments. In order to achieve that, the default processing thresholds are very conservative.
Specifically, Action Scheduler will only process actions until:
* 90% of available memory is used
* processing another 3 actions would exceed 30 seconds of total request time, based on the average processing time for the current batch
On sites with large queues, this can result in very slow processing time.
While using [WP CLI to process queues](/wp-cli/) is the best approach to increasing processing speed, on occasion, that is not a viable option. In these cases, it's also possible to increase the processing thresholds in Action Scheduler to increase the rate at which actions are processed by the default WP Cron queue runner.
## Increasing Time Limit
By default, Action Scheduler will only process actions for a maximum of 30 seconds. This time limit minimises the risk of a script timeout on unknown hosting environments, some of which enforce 30 second timeouts.
If you know your host supports longer than this time limit for web requests, you can increase this time limit. This allows more actions to be processed in each request and reduces the lag between processing each queue, greating speeding up the processing rate of scheduled actions.
For example, the following snippet will increase the timelimit to 2 minutes (120 seconds):
```php
function eg_increase_time_limit( $time_limit ) {
return 120;
}
add_filter( 'action_scheduler_queue_runner_time_limit', 'eg_increase_time_limit' );
```
Some of the known host time limits are:
* 60 second on WP Engine
* 120 seconds on Pantheon
* 120 seconds on SiteGround
## Increasing Batch Size
By default, Action Scheduler will claim a batch of 25 actions. This small batch size is because the default time limit is only 30 seconds; however, if you know your actions are processing very quickly, e.g. taking microseconds not seconds, or that you have more than 30 second available to process each batch, increasing the batch size can improve performance.
This is because claiming a batch has some overhead, so the less often a batch needs to be claimed, the faster actions can be processed.
For example, to increase the batch size to 100, we can use the following function:
```php
function eg_increase_action_scheduler_batch_size( $batch_size ) {
return 100;
}
add_filter( 'action_scheduler_queue_runner_batch_size', 'eg_increase_action_scheduler_batch_size' );
```
## Increasing Concurrent Batches
By default, Action Scheduler will run up to 5 concurrent batches of actions. This is to prevent consuming all the available connections or processes on your webserver.
However, your server may allow a large number of connection, for example, because it has a high value for Apache's `MaxClients` setting or PHP-FPM's `pm.max_children` setting.
If this is the case, you can use the `'action_scheduler_queue_runner_concurrent_batches'` filter to increase the number of conncurrent batches allowed, and therefore speed up processing large numbers of actions scheduled to be processed simultaneously.
For example, to increase the allowed number of concurrent queues to 10, we can use the following code:
```php
function eg_increase_action_scheduler_concurrent_batches( $concurrent_batches ) {
return 10;
}
add_filter( 'action_scheduler_queue_runner_concurrent_batches', 'eg_increase_action_scheduler_concurrent_batches' );
```
## Increasing Initialisation Rate of Runners
By default, Action scheduler initiates at most, one queue runner every time the `'action_scheduler_run_queue'` action is triggered by WP Cron.
Because this action is only triggered at most once every minute, if a queue is only allowed to process for one minute, then there will never be more than one queue processing actions, greatly reducing the processing rate.
To handle larger queues on more powerful servers, it's a good idea to initiate additional queue runners whenever the `'action_scheduler_run_queue'` action is run.
That can be done by initiated additional secure requests to our server via loopback requests.
The code below demonstrates how to create 5 loopback requests each time a queue begins
```php
/**
* Trigger 5 additional loopback requests with unique URL params.
*/
function eg_request_additional_runners() {
// allow self-signed SSL certificates
add_filter( 'https_local_ssl_verify', '__return_false', 100 );
for ( $i = 0; $i < 5; $i++ ) {
$response = wp_remote_post( admin_url( 'admin-ajax.php' ), array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => false,
'headers' => array(),
'body' => array(
'action' => 'eg_create_additional_runners',
'instance' => $i,
'eg_nonce' => wp_create_nonce( 'eg_additional_runner_' . $i ),
),
'cookies' => array(),
) );
}
}
add_action( 'action_scheduler_run_queue', 'eg_request_additional_runners', 0 );
/**
* Handle requests initiated by eg_request_additional_runners() and start a queue runner if the request is valid.
*/
function eg_create_additional_runners() {
if ( isset( $_POST['eg_nonce'] ) && isset( $_POST['instance'] ) && wp_verify_nonce( $_POST['eg_nonce'], 'eg_additional_runner_' . $_POST['instance'] ) ) {
ActionScheduler_QueueRunner::instance()->run();
}
wp_die();
}
add_action( 'wp_ajax_nopriv_eg_create_additional_runners', 'eg_create_additional_runners', 0 );
```
## High Volume Plugin
It's not necessary to add all of this code yourself, the folks at [Prospress](https://prospress.com) have created a handy plugin to get access to each of these increases - the [Action Scheduler - High Volume](https://github.com/prospress/action-scheduler-high-volume) plugin.

View File

@ -1,40 +0,0 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
width="312.000000pt" height="312.000000pt" viewBox="0 0 312.000000 312.000000"
preserveAspectRatio="xMidYMid meet">
<metadata>
Created by potrace 1.11, written by Peter Selinger 2001-2013
</metadata>
<g transform="translate(0.000000,312.000000) scale(0.100000,-0.100000)"
fill="#000000" stroke="none">
<path d="M1837 2924 c-1 -1 -54 -5 -117 -8 -63 -4 -128 -9 -145 -11 -16 -2
-46 -6 -65 -9 -19 -3 -57 -8 -85 -11 -27 -3 -70 -10 -95 -16 -25 -5 -58 -11
-75 -13 -98 -13 -360 -73 -565 -130 -236 -65 -584 -172 -609 -187 -105 -67 24
-294 221 -387 77 -37 152 -61 206 -65 16 -1 22 -8 22 -23 0 -34 35 -107 70
-147 62 -71 161 -119 265 -130 34 -4 40 -8 46 -33 25 -122 151 -205 301 -198
122 5 254 44 270 80 6 13 8 27 5 30 -3 4 -41 1 -84 -5 -119 -18 -155 -19 -217
-9 -74 11 -123 47 -132 94 -7 40 -4 46 28 49 94 12 238 52 260 72 35 32 23 46
-34 38 -29 -4 -62 -9 -73 -11 -45 -10 -255 -11 -320 -2 -81 11 -154 40 -185
73 -24 26 -52 97 -42 106 4 4 45 9 92 12 93 7 90 6 269 43 69 14 134 30 145
36 29 15 56 39 56 50 0 10 -74 3 -144 -12 -22 -5 -144 -8 -270 -6 -251 3 -327
15 -443 71 -47 23 -133 97 -133 115 0 6 150 49 225 64 11 3 83 20 160 39 77
19 154 38 170 41 17 4 39 8 50 10 11 3 56 12 100 21 98 21 104 22 146 29 19 3
43 7 54 10 28 5 94 16 130 20 17 3 44 7 60 10 17 2 50 7 75 11 41 5 87 11 150
20 111 16 452 23 509 11 14 -3 47 -8 75 -11 28 -3 78 -13 111 -21 365 -92 513
-289 509 -679 -1 -102 -35 -265 -56 -265 -5 0 -7 -4 -4 -9 3 -4 -12 -41 -33
-81 -144 -277 -468 -551 -794 -671 -107 -39 -317 -88 -317 -73 0 2 50 118 111
257 61 138 131 299 156 357 25 58 49 114 54 125 5 11 52 119 104 240 90 208
94 221 84 255 -19 58 -67 147 -99 183 -33 38 -86 65 -99 51 -5 -5 -23 -43 -41
-84 -50 -116 -179 -408 -211 -478 -16 -35 -29 -65 -29 -67 0 -2 -18 -43 -40
-90 -22 -47 -40 -88 -40 -90 0 -4 -92 -211 -156 -353 -13 -29 -24 -55 -24 -57
0 -2 -15 -37 -34 -77 -18 -40 -46 -102 -61 -138 -16 -36 -45 -102 -67 -148
-21 -46 -38 -85 -38 -87 0 -2 -34 -81 -76 -175 -55 -124 -74 -178 -70 -196 16
-62 116 -134 207 -148 36 -5 37 -5 63 53 14 32 51 112 82 177 31 66 74 160 96
209 22 50 43 93 47 98 7 7 19 10 82 21 19 3 44 8 55 10 12 2 38 7 57 10 480
76 883 299 1117 618 100 135 202 363 224 498 1 8 5 35 9 60 16 95 13 216 -7
340 -10 59 -60 190 -97 252 -45 76 -151 190 -219 235 -127 85 -324 159 -475
179 -27 3 -53 8 -56 9 -12 8 -344 25 -352 19z"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.5 KiB

View File

@ -1,19 +0,0 @@
{
"name": "",
"short_name": "",
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/android-chrome-256x256.png",
"sizes": "256x256",
"type": "image/png"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
}

View File

@ -1,123 +0,0 @@
---
description: Learn how to use the Action Scheduler background processing job queue for WordPress in your WordPress plugin.
---
# Usage
Using Action Scheduler requires:
1. installing the library
1. scheduling and action
1. attaching a callback to that action
## Scheduling an Action
To schedule an action, call the [API function](/api/) for the desired schedule type passing in the required parameters.
The example code below shows everything needed to schedule a function to run at midnight, if it's not already scheduled:
```php
require_once( plugin_dir_path( __FILE__ ) . '/libraries/action-scheduler/action-scheduler.php' );
/**
* Schedule an action with the hook 'eg_midnight_log' to run at midnight each day
* so that our callback is run then.
*/
function eg_log_action_data() {
if ( false === as_next_scheduled_action( 'eg_midnight_log' ) ) {
as_schedule_recurring_action( strtotime( 'midnight tonight' ), DAY_IN_SECONDS, 'eg_midnight_log' );
}
}
add_action( 'init', 'eg_log_action_data' );
/**
* A callback to run when the 'eg_midnight_log' scheduled action is run.
*/
function eg_log_action_data() {
error_log( 'It is just after midnight on ' . date( 'Y-m-d' ) );
}
add_action( 'eg_midnight_log', 'eg_log_action_data' );
```
For more details on all available API functions, and the data they accept, refer to the [API Reference](/api/).
## Installation
There are two ways to install Action Scheduler:
1. regular WordPress plugin; or
1. a library within your plugin's codebase.
### Usage as a Plugin
Action Scheduler includes the necessary file headers to be used as a standard WordPress plugin.
To install it as a plugin:
1. Download the .zip archive of the latest [stable release](https://github.com/Prospress/action-scheduler/releases)
1. Go to the **Plugins > Add New > Upload** administration screen on your WordPress site
1. Select the archive file you just downloaded
1. Click **Install Now**
1. Click **Activate**
Or clone the Git repository into your site's `wp-content/plugins` folder.
Using Action Scheduler as a plugin can be handy for developing against newer versions, rather than having to update the subtree in your codebase. **When installed as a plugin, Action Scheduler does not provide any user interfaces for scheduling actions**. The only way to interact with Action Scheduler is via code.
### Usage as a Library
To use Action Scheduler as a library:
1. include the Action Scheduler codebase
1. load the library by including the `action-scheduler.php` file
Using a [subtree in your plugin, theme or site's Git repository](https://www.atlassian.com/blog/git/alternatives-to-git-submodule-git-subtree) to include Action Scheduler is the recommended method. Composer can also be used.
To include Action Scheduler as a git subtree:
#### Step 1. Add the Repository as a Remote
```
git remote add -f subtree-action-scheduler https://github.com/Prospress/action-scheduler.git
```
Adding the subtree as a remote allows us to refer to it in short from via the name `subtree-action-scheduler`, instead of the full GitHub URL.
#### Step 2. Add the Repo as a Subtree
```
git subtree add --prefix libraries/action-scheduler subtree-action-scheduler master --squash
```
This will add the `master` branch of Action Scheduler to your repository in the folder `libraries/action-scheduler`.
You can change the `--prefix` to change where the code is included. Or change the `master` branch to a tag, like `2.1.0` to include only a stable version.
#### Step 3. Update the Subtree
To update Action Scheduler to a new version, use the commands:
```
git fetch subtree-action-scheduler master
git subtree pull --prefix libraries/action-scheduler subtree-action-scheduler master --squash
```
### Loading Action Scheduler
Regardless of how it is installed, to load Action Scheduler, you only need to include the `action-scheduler.php` file, e.g.
```php
<?php
require_once( plugin_dir_path( __FILE__ ) . '/libraries/action-scheduler/action-scheduler.php' );
```
There is no need to call any functions or do else to initialize Action Scheduler.
When the `action-scheduler.php` file is included, Action Scheduler will register the version in that file and then load the most recent version of itself on the site. It will also load the most recent version of [all API functions](https://github.com/prospress/action-scheduler#api-functions).
### Load Order
Action Scheduler will register its version on `'plugins_loaded'` with priority `0` - after all other plugin codebases has been loaded. Therefore **the `action-scheduler.php` file must be included before `'plugins_loaded'` priority `0`**.
It is recommended to load it _when the file including it is included_. However, if you need to load it on a hook, then the hook must occur before `'plugins_loaded'`, or you can use `'plugins_loaded'` with negative priority, like `-10`.
Action Scheduler will later initialize itself on `'init'` with priority `1`. Action Scheduler APIs should not be used until after `'init'` with priority `1`.

View File

@ -1,73 +0,0 @@
---
description: Learn how to do WordPress background processing at scale with WP CLI and the Action Scheduler job queue.
---
# WP CLI
Action Scheduler has custom [WP CLI](http://wp-cli.org) commands available for processing actions.
For large sites, WP CLI is a much better choice for running queues of actions than the default WP Cron runner. These are some common cases where WP CLI is a better option:
* long-running tasks - Tasks that take a significant amount of time to run
* large queues - A large number of tasks will naturally take a longer time
* other plugins with extensive WP Cron usage - WP Cron's limited resources are spread across more tasks
With a regular web request, you may have to deal with script timeouts enforced by hosts, or other restraints that make it more challenging to run Action Scheduler tasks. Utilizing WP CLI to run commands directly on the server give you more freedom. This means that you typically don't have the same constraints of a normal web request.
If you choose to utilize WP CLI exclusively, you can disable the normal WP CLI queue runner by installing the [Action Scheduler - Disable Default Queue Runner](https://github.com/Prospress/action-scheduler-disable-default-runner) plugin. Note that if you do this, you **must** run Action Scheduler via WP CLI or another method, otherwise no scheduled actions will be processed.
## Commands
These are the commands available to use with Action Scheduler:
* `action-scheduler run`
Options:
* `--batch-size` - This is the number of actions to run in a single batch. The default is `100`.
* `--batches` - This is the number of batches to run. Using 0 means that batches will continue running until there are no more actions to run.
* `--hooks` - Process only actions with specific hook or hooks, like `'woocommerce_scheduled_subscription_payment'`. By default, actions with any hook will be processed. Define multiple hooks as a comma separated string (without spaces), e.g. `--hooks=woocommerce_scheduled_subscription_trial_end,woocommerce_scheduled_subscription_payment,woocommerce_scheduled_subscription_expiration`
* `--group` - Process only actions in a specific group, like `'woocommerce-memberships'`. By default, actions in any group (or no group) will be processed.
* `--force` - By default, Action Scheduler limits the number of concurrent batches that can be run at once to ensure the server does not get overwhelmed. Using the `--force` flag overrides this behavior to force the WP CLI queue to run.
The best way to get a full list of commands and their available options is to use WP CLI itself. This can be done by running `wp action-scheduler` to list all Action Scheduler commands, or by including the `--help` flag with any of the individual commands. This will provide all relevant parameters and flags for the command.
## Cautionary Note on Action Dependencies when using `--group` or `--hooks` Options
The `--group` and `--hooks` options should be used with caution if you have an implicit dependency between scheduled actions based on their schedule.
For example, consider two scheduled actions for the same subscription:
* `scheduled_payment` scheduled for `2015-11-13 00:00:00` and
* `scheduled_expiration` scheduled for `2015-11-13 00:01:00`.
Under normal conditions, Action Scheduler will ensure the `scheduled_payment` action is run before the `scheduled_expiration` action. Becuase that's how they are scheduled.
However, when using the `--hooks` option, the `scheduled_payment` and `scheduled_expiration` actions will be processed in separate queues. As a result, this dependency is not guaranteed.
For example, consider a site with both:
* 100,000 `scheduled_payment` actions, scheduled for `2015-11-13 00:00:00`
* 100 `scheduled_expiration` actions, scheduled for `2015-11-13 00:01:00`
If two queue runners are running alongside each other with each runner dedicated to just one of these hooks, the queue runner handling expiration hooks will complete the processing of the expiration hooks more quickly than the queue runner handling all the payment actions.
**Because of this, the `--group` and `--hooks` options should be used with caution to avoid processing actions with an implicit dependency based on their schedule in separate queues.**
## Improving Performance with `--group` or `--hooks`
Being able to run queues for specific hooks or groups of actions is valuable at scale. Why? Because it means you can restrict the concurrency for similar actions.
For example, let's say you have 300,000 actions queued up comprised of:
* 100,000 renewals payments
* 100,000 email notifications
* 100,000 membership status updates
Action Scheduler's default WP Cron queue runner will process them all together. e.g. when it claims a batch of actions, some may be emails, some membership updates and some renewals.
When you add concurrency to that, you can end up with issues. For example, if you have 3 queues running, they may all be attempting to process similar actions at the same time, which can lead to querying the same database tables with similar queries. Depending on the code/queries running, this can lead to database locks or other issues.
If you can batch based on each action's group, then you can improve performance by processing like actions consecutively, but still processing the full set of actions concurrently.
For example, if one queue is created to process emails, another to process membership updates, and another to process renewal payments, then the same queries won't be run at the same time, and 3 separate queues will be able to run more efficiently.
The WP CLI runner can achieve this using the `--group` option.

View File

@ -1,44 +0,0 @@
<?php
/**
* Class ActionScheduler_UnitTestCase
*/
class ActionScheduler_UnitTestCase extends WP_UnitTestCase {
protected $existing_timezone;
/**
* Counts the number of test cases executed by run(TestResult result).
*
* @return int
*/
public function count() {
return 'UTC' == date_default_timezone_get() ? 2 : 3;
}
/**
* We want to run every test multiple times using a different timezone to make sure
* that they are unaffected by changes to PHP's timezone.
*/
public function run( PHPUnit\Framework\TestResult $result = NULL ){
if ($result === NULL) {
$result = $this->createResult();
}
if ( 'UTC' != ( $this->existing_timezone = date_default_timezone_get() ) ) {
date_default_timezone_set( 'UTC' );
$result->run( $this );
}
date_default_timezone_set( 'Pacific/Fiji' ); // UTC+12
$result->run( $this );
date_default_timezone_set( 'Pacific/Tahiti' ); // UTC-10: it's a magical place
$result->run( $this );
date_default_timezone_set( $this->existing_timezone );
return $result;
}
}

View File

@ -1,31 +0,0 @@
<?php
$GLOBALS['wp_tests_options'][ 'template' ] = 'twentyseventeen';
$GLOBALS['wp_tests_options'][ 'stylesheet' ] = 'twentyseventeen';
$GLOBALS['wp_tests_options'][ 'active_plugins' ][] = basename( dirname( __DIR__ ) ) .'/action-scheduler.php';
// Check for select constants defined as environment variables
foreach ( array('WP_CONTENT_DIR', 'WP_CONTENT_URL', 'WP_PLUGIN_DIR', 'WP_PLUGIN_URL', 'WPMU_PLUGIN_DIR') as $env_constant ) {
if ( false !== getenv( $env_constant ) && !defined( $env_constant ) ) {
define( $env_constant, getenv( $env_constant ));
}
}
// If the wordpress-tests repo location has been customized (and specified
// with WP_TESTS_DIR), use that location. This will most commonly be the case
// when configured for use with Travis CI.
// Otherwise, we'll just assume that this plugin is installed in the WordPress
// SVN external checkout configured in the wordpress-tests repo.
if( false !== getenv( 'WP_TESTS_DIR' ) ) {
require getenv( 'WP_TESTS_DIR' ) . '/includes/bootstrap.php';
} else {
require dirname( dirname( dirname( dirname( dirname( dirname( __FILE__ ) ) ) ) ) ) . '/tests/phpunit/includes/bootstrap.php';
}
if ( class_exists( 'PHPUnit\Framework\TestResult' ) ) { // PHPUnit 6.0 or newer
include_once('ActionScheduler_UnitTestCase.php');
} else {
include_once('phpunit/deprecated/ActionScheduler_UnitTestCase.php');
}

View File

@ -1,32 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="bootstrap.php"
>
<testsuites>
<testsuite name="Action Scheduler">
<directory>./phpunit</directory>
</testsuite>
</testsuites>
<groups>
<exclude>
<group>ignore</group>
</exclude>
</groups>
<filter>
<whitelist processsUncoveredFilesFromWhitelist="true">
<directory suffix=".php">..</directory>
<exclude>
<directory>.</directory>
</exclude>
</whitelist>
</filter>
</phpunit>

View File

@ -1,44 +0,0 @@
<?php
/**
* Class ActionScheduler_UnitTestCase
*/
class ActionScheduler_UnitTestCase extends WP_UnitTestCase {
protected $existing_timezone;
/**
* Counts the number of test cases executed by run(TestResult result).
*
* @return int
*/
public function count() {
return 'UTC' == date_default_timezone_get() ? 2 : 3;
}
/**
* We want to run every test multiple times using a different timezone to make sure
* that they are unaffected by changes to PHP's timezone.
*/
public function run( PHPUnit_Framework_TestResult $result = NULL ){
if ($result === NULL) {
$result = $this->createResult();
}
if ( 'UTC' != ( $this->existing_timezone = date_default_timezone_get() ) ) {
date_default_timezone_set( 'UTC' );
$result->run( $this );
}
date_default_timezone_set( 'Pacific/Fiji' ); // UTC+12
$result->run( $this );
date_default_timezone_set( 'Pacific/Tahiti' ); // UTC-10: it's a magical place
$result->run( $this );
date_default_timezone_set( $this->existing_timezone );
return $result;
}
}

View File

@ -1,100 +0,0 @@
<?php
/**
* @group timezone
*/
class ActionScheduler_TimezoneHelper_Test extends ActionScheduler_UnitTestCase {
/**
* Ensure that the timezone string we expect works properly.
*
* @dataProvider local_timezone_provider
*
* @param $timezone_string
*/
public function test_local_timezone_strings( $timezone_string ) {
$timezone_filter = function ( $tz ) use ( $timezone_string ) {
return $timezone_string;
};
add_filter( 'option_timezone_string', $timezone_filter );
$date = new ActionScheduler_DateTime();
$timezone = ActionScheduler_TimezoneHelper::set_local_timezone( $date )->getTimezone();
$this->assertInstanceOf( 'DateTimeZone', $timezone );
$this->assertEquals( $timezone_string, $timezone->getName() );
remove_filter( 'option_timezone_string', $timezone_filter );
}
public function local_timezone_provider() {
return array(
array( 'America/New_York' ),
array( 'Australia/Melbourne' ),
array( 'UTC' ),
);
}
/**
* Ensure that most GMT offsets don't return UTC as the timezone.
*
* @dataProvider local_timezone_offsets_provider
*
* @param $gmt_offset
*/
public function test_local_timezone_offsets( $gmt_offset ) {
$gmt_filter = function ( $gmt ) use ( $gmt_offset ) {
return $gmt_offset;
};
$date = new ActionScheduler_DateTime();
add_filter( 'option_gmt_offset', $gmt_filter );
ActionScheduler_TimezoneHelper::set_local_timezone( $date );
remove_filter( 'option_gmt_offset', $gmt_filter );
$offset_in_seconds = $gmt_offset * HOUR_IN_SECONDS;
$this->assertEquals( $offset_in_seconds, $date->getOffset() );
$this->assertEquals( $offset_in_seconds, $date->getOffsetTimestamp() - $date->getTimestamp() );
}
public function local_timezone_offsets_provider() {
return array(
array( '-11' ),
array( '-10.5' ),
array( '-10' ),
array( '-9' ),
array( '-8' ),
array( '-7' ),
array( '-6' ),
array( '-5' ),
array( '-4.5' ),
array( '-4' ),
array( '-3.5' ),
array( '-3' ),
array( '-2' ),
array( '-1' ),
array( '1' ),
array( '1.5' ),
array( '2' ),
array( '3' ),
array( '4' ),
array( '5' ),
array( '5.5' ),
array( '5.75' ),
array( '6' ),
array( '7' ),
array( '8' ),
array( '8.5' ),
array( '9' ),
array( '9.5' ),
array( '10' ),
array( '10.5' ),
array( '11' ),
array( '11.5' ),
array( '12' ),
array( '13' ),
);
}
}

View File

@ -1,55 +0,0 @@
<?php
/**
* Class ActionScheduler_Action_Test
* @group actions
*/
class ActionScheduler_Action_Test extends ActionScheduler_UnitTestCase {
public function test_set_schedule() {
$time = as_get_datetime_object();
$schedule = new ActionScheduler_SimpleSchedule($time);
$action = new ActionScheduler_Action('my_hook', array(), $schedule);
$this->assertEquals( $schedule, $action->get_schedule() );
}
public function test_null_schedule() {
$action = new ActionScheduler_Action('my_hook');
$this->assertInstanceOf( 'ActionScheduler_NullSchedule', $action->get_schedule() );
}
public function test_set_hook() {
$action = new ActionScheduler_Action('my_hook');
$this->assertEquals( 'my_hook', $action->get_hook() );
}
public function test_args() {
$action = new ActionScheduler_Action('my_hook');
$this->assertEmpty($action->get_args());
$action = new ActionScheduler_Action('my_hook', array(5,10,15));
$this->assertEqualSets(array(5,10,15), $action->get_args());
}
public function test_set_group() {
$action = new ActionScheduler_Action('my_hook', array(), NULL, 'my_group');
$this->assertEquals('my_group', $action->get_group());
}
public function test_execute() {
$mock = new MockAction();
$random = md5(rand());
add_action( $random, array( $mock, 'action' ) );
$action = new ActionScheduler_Action( $random, array($random) );
$action->execute();
remove_action( $random, array( $mock, 'action' ) );
$this->assertEquals( 1, $mock->get_call_count() );
$events = $mock->get_events();
$event = reset($events);
$this->assertEquals( $random, reset($event['args']) );
}
}

View File

@ -1,16 +0,0 @@
<?php
/**
* Class ActionScheduler_NullAction_Test
* @group actions
*/
class ActionScheduler_NullAction_Test extends ActionScheduler_UnitTestCase {
public function test_null_action() {
$action = new ActionScheduler_NullAction();
$this->assertEmpty($action->get_hook());
$this->assertEmpty($action->get_args());
$this->assertNull($action->get_schedule()->next());
}
}

View File

@ -1,375 +0,0 @@
<?php
/**
* Class ActionScheduler_wpPostStore_Test
* @group stores
*/
class ActionScheduler_wpPostStore_Test extends ActionScheduler_UnitTestCase {
public function test_create_action() {
$time = as_get_datetime_object();
$schedule = new ActionScheduler_SimpleSchedule($time);
$action = new ActionScheduler_Action('my_hook', array(), $schedule);
$store = new ActionScheduler_wpPostStore();
$action_id = $store->save_action($action);
$this->assertNotEmpty($action_id);
}
public function test_create_action_with_scheduled_date() {
$time = as_get_datetime_object( strtotime( '-1 week' ) );
$action = new ActionScheduler_Action( 'my_hook', array(), new ActionScheduler_SimpleSchedule( $time ) );
$store = new ActionScheduler_wpPostStore();
$action_id = $store->save_action( $action, $time );
$action_date = $store->get_date( $action_id );
$this->assertEquals( $time->getTimestamp(), $action_date->getTimestamp() );
}
public function test_retrieve_action() {
$time = as_get_datetime_object();
$schedule = new ActionScheduler_SimpleSchedule($time);
$action = new ActionScheduler_Action('my_hook', array(), $schedule, 'my_group');
$store = new ActionScheduler_wpPostStore();
$action_id = $store->save_action($action);
$retrieved = $store->fetch_action($action_id);
$this->assertEquals($action->get_hook(), $retrieved->get_hook());
$this->assertEqualSets($action->get_args(), $retrieved->get_args());
$this->assertEquals($action->get_schedule()->next()->getTimestamp(), $retrieved->get_schedule()->next()->getTimestamp());
$this->assertEquals($action->get_group(), $retrieved->get_group());
}
/**
* @expectedException ActionScheduler_InvalidActionException
* @dataProvider provide_bad_args
*
* @param string $content
*/
public function test_action_bad_args( $content ) {
$store = new ActionScheduler_wpPostStore();
$post_id = wp_insert_post( array(
'post_type' => ActionScheduler_wpPostStore::POST_TYPE,
'post_status' => ActionScheduler_Store::STATUS_PENDING,
'post_content' => $content,
) );
$store->fetch_action( $post_id );
}
public function provide_bad_args() {
return array(
array( '{"bad_json":true}}' ),
);
}
public function test_cancel_action() {
$time = as_get_datetime_object();
$schedule = new ActionScheduler_SimpleSchedule($time);
$action = new ActionScheduler_Action('my_hook', array(), $schedule, 'my_group');
$store = new ActionScheduler_wpPostStore();
$action_id = $store->save_action($action);
$store->cancel_action( $action_id );
$fetched = $store->fetch_action( $action_id );
$this->assertInstanceOf( 'ActionScheduler_CanceledAction', $fetched );
}
public function test_claim_actions() {
$created_actions = array();
$store = new ActionScheduler_wpPostStore();
for ( $i = 3 ; $i > -3 ; $i-- ) {
$time = as_get_datetime_object($i.' hours');
$schedule = new ActionScheduler_SimpleSchedule($time);
$action = new ActionScheduler_Action('my_hook', array($i), $schedule, 'my_group');
$created_actions[] = $store->save_action($action);
}
$claim = $store->stake_claim();
$this->assertInstanceof( 'ActionScheduler_ActionClaim', $claim );
$this->assertCount( 3, $claim->get_actions() );
$this->assertEqualSets( array_slice( $created_actions, 3, 3 ), $claim->get_actions() );
}
public function test_claim_actions_order() {
$store = new ActionScheduler_wpPostStore();
$schedule = new ActionScheduler_SimpleSchedule( as_get_datetime_object( '-1 hour' ) );
$created_actions = array(
$store->save_action( new ActionScheduler_Action( 'my_hook', array( 1 ), $schedule, 'my_group' ) ),
$store->save_action( new ActionScheduler_Action( 'my_hook', array( 1 ), $schedule, 'my_group' ) ),
);
$claim = $store->stake_claim();
$this->assertInstanceof( 'ActionScheduler_ActionClaim', $claim );
// Verify uniqueness of action IDs.
$this->assertEquals( 2, count( array_unique( $created_actions ) ) );
// Verify the count and order of the actions.
$claimed_actions = $claim->get_actions();
$this->assertCount( 2, $claimed_actions );
$this->assertEquals( $created_actions, $claimed_actions );
// Verify the reversed order doesn't pass.
$reversed_actions = array_reverse( $created_actions );
$this->assertNotEquals( $reversed_actions, $claimed_actions );
}
public function test_duplicate_claim() {
$created_actions = array();
$store = new ActionScheduler_wpPostStore();
for ( $i = 0 ; $i > -3 ; $i-- ) {
$time = as_get_datetime_object($i.' hours');
$schedule = new ActionScheduler_SimpleSchedule($time);
$action = new ActionScheduler_Action('my_hook', array($i), $schedule, 'my_group');
$created_actions[] = $store->save_action($action);
}
$claim1 = $store->stake_claim();
$claim2 = $store->stake_claim();
$this->assertCount( 3, $claim1->get_actions() );
$this->assertCount( 0, $claim2->get_actions() );
}
public function test_release_claim() {
$created_actions = array();
$store = new ActionScheduler_wpPostStore();
for ( $i = 0 ; $i > -3 ; $i-- ) {
$time = as_get_datetime_object($i.' hours');
$schedule = new ActionScheduler_SimpleSchedule($time);
$action = new ActionScheduler_Action('my_hook', array($i), $schedule, 'my_group');
$created_actions[] = $store->save_action($action);
}
$claim1 = $store->stake_claim();
$store->release_claim( $claim1 );
$claim2 = $store->stake_claim();
$this->assertCount( 3, $claim2->get_actions() );
}
public function test_search() {
$created_actions = array();
$store = new ActionScheduler_wpPostStore();
for ( $i = -3 ; $i <= 3 ; $i++ ) {
$time = as_get_datetime_object($i.' hours');
$schedule = new ActionScheduler_SimpleSchedule($time);
$action = new ActionScheduler_Action('my_hook', array($i), $schedule, 'my_group');
$created_actions[] = $store->save_action($action);
}
$next_no_args = $store->find_action( 'my_hook' );
$this->assertEquals( $created_actions[0], $next_no_args );
$next_with_args = $store->find_action( 'my_hook', array( 'args' => array( 1 ) ) );
$this->assertEquals( $created_actions[4], $next_with_args );
$non_existent = $store->find_action( 'my_hook', array( 'args' => array( 17 ) ) );
$this->assertNull( $non_existent );
}
public function test_search_by_group() {
$store = new ActionScheduler_wpPostStore();
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('tomorrow'));
$abc = $store->save_action(new ActionScheduler_Action('my_hook', array(1), $schedule, 'abc'));
$def = $store->save_action(new ActionScheduler_Action('my_hook', array(1), $schedule, 'def'));
$ghi = $store->save_action(new ActionScheduler_Action('my_hook', array(1), $schedule, 'ghi'));
$this->assertEquals( $abc, $store->find_action('my_hook', array('group' => 'abc')));
$this->assertEquals( $def, $store->find_action('my_hook', array('group' => 'def')));
$this->assertEquals( $ghi, $store->find_action('my_hook', array('group' => 'ghi')));
}
public function test_post_author() {
$current_user = get_current_user_id();
$time = as_get_datetime_object();
$schedule = new ActionScheduler_SimpleSchedule($time);
$action = new ActionScheduler_Action('my_hook', array(), $schedule);
$store = new ActionScheduler_wpPostStore();
$action_id = $store->save_action($action);
$post = get_post($action_id);
$this->assertEquals(0, $post->post_author);
$new_user = $this->factory->user->create_object(array(
'user_login' => __FUNCTION__,
'user_pass' => md5(rand()),
));
wp_set_current_user( $new_user );
$schedule = new ActionScheduler_SimpleSchedule($time);
$action = new ActionScheduler_Action('my_hook', array(), $schedule);
$action_id = $store->save_action($action);
$post = get_post($action_id);
$this->assertEquals(0, $post->post_author);
wp_set_current_user($current_user);
}
/**
* @issue 13
*/
public function test_post_status_for_recurring_action() {
$time = as_get_datetime_object('10 minutes');
$schedule = new ActionScheduler_IntervalSchedule($time, HOUR_IN_SECONDS);
$action = new ActionScheduler_Action('my_hook', array(), $schedule);
$store = new ActionScheduler_wpPostStore();
$action_id = $store->save_action($action);
$action = $store->fetch_action($action_id);
$action->execute();
$store->mark_complete( $action_id );
$next = $action->get_schedule()->next( as_get_datetime_object() );
$new_action_id = $store->save_action( $action, $next );
$this->assertEquals('publish', get_post_status($action_id));
$this->assertEquals('pending', get_post_status($new_action_id));
}
public function test_get_run_date() {
$time = as_get_datetime_object('-10 minutes');
$schedule = new ActionScheduler_IntervalSchedule($time, HOUR_IN_SECONDS);
$action = new ActionScheduler_Action('my_hook', array(), $schedule);
$store = new ActionScheduler_wpPostStore();
$action_id = $store->save_action($action);
$this->assertEquals( $store->get_date($action_id)->getTimestamp(), $time->getTimestamp() );
$action = $store->fetch_action($action_id);
$action->execute();
$now = as_get_datetime_object();
$store->mark_complete( $action_id );
$this->assertEquals( $store->get_date($action_id)->getTimestamp(), $now->getTimestamp() );
$next = $action->get_schedule()->next( $now );
$new_action_id = $store->save_action( $action, $next );
$this->assertEquals( (int)($now->getTimestamp()) + HOUR_IN_SECONDS, $store->get_date($new_action_id)->getTimestamp() );
}
public function test_get_status() {
$time = as_get_datetime_object('-10 minutes');
$schedule = new ActionScheduler_IntervalSchedule($time, HOUR_IN_SECONDS);
$action = new ActionScheduler_Action('my_hook', array(), $schedule);
$store = new ActionScheduler_wpPostStore();
$action_id = $store->save_action($action);
$this->assertEquals( ActionScheduler_Store::STATUS_PENDING, $store->get_status( $action_id ) );
$store->mark_complete( $action_id );
$this->assertEquals( ActionScheduler_Store::STATUS_COMPLETE, $store->get_status( $action_id ) );
$store->mark_failure( $action_id );
$this->assertEquals( ActionScheduler_Store::STATUS_FAILED, $store->get_status( $action_id ) );
}
public function test_claim_actions_by_hooks() {
$hook1 = __FUNCTION__ . '_hook_1';
$hook2 = __FUNCTION__ . '_hook_2';
$store = new ActionScheduler_wpPostStore();
$schedule = new ActionScheduler_SimpleSchedule( as_get_datetime_object( '-1 hour' ) );
$action1 = $store->save_action( new ActionScheduler_Action( $hook1, array(), $schedule ) );
$action2 = $store->save_action( new ActionScheduler_Action( $hook2, array(), $schedule ) );
// Claiming no hooks should include all actions.
$claim = $store->stake_claim( 10 );
$this->assertEquals( 2, count( $claim->get_actions() ) );
$this->assertTrue( in_array( $action1, $claim->get_actions() ) );
$this->assertTrue( in_array( $action2, $claim->get_actions() ) );
$store->release_claim( $claim );
// Claiming a hook should claim only actions with that hook
$claim = $store->stake_claim( 10, null, array( $hook1 ) );
$this->assertEquals( 1, count( $claim->get_actions() ) );
$this->assertTrue( in_array( $action1, $claim->get_actions() ) );
$store->release_claim( $claim );
// Claiming two hooks should claim actions with either of those hooks
$claim = $store->stake_claim( 10, null, array( $hook1, $hook2 ) );
$this->assertEquals( 2, count( $claim->get_actions() ) );
$this->assertTrue( in_array( $action1, $claim->get_actions() ) );
$this->assertTrue( in_array( $action2, $claim->get_actions() ) );
$store->release_claim( $claim );
// Claiming two hooks should claim actions with either of those hooks
$claim = $store->stake_claim( 10, null, array( __METHOD__ . '_hook_3' ) );
$this->assertEquals( 0, count( $claim->get_actions() ) );
$this->assertFalse( in_array( $action1, $claim->get_actions() ) );
$this->assertFalse( in_array( $action2, $claim->get_actions() ) );
$store->release_claim( $claim );
}
/**
* @issue 121
*/
public function test_claim_actions_by_group() {
$group1 = md5( rand() );
$store = new ActionScheduler_wpPostStore();
$schedule = new ActionScheduler_SimpleSchedule( as_get_datetime_object( '-1 hour' ) );
$action1 = $store->save_action( new ActionScheduler_Action( __METHOD__, array(), $schedule, $group1 ) );
$action2 = $store->save_action( new ActionScheduler_Action( __METHOD__, array(), $schedule ) );
// Claiming no group should include all actions.
$claim = $store->stake_claim( 10 );
$this->assertEquals( 2, count( $claim->get_actions() ) );
$this->assertTrue( in_array( $action1, $claim->get_actions() ) );
$this->assertTrue( in_array( $action2, $claim->get_actions() ) );
$store->release_claim( $claim );
// Claiming a group should claim only actions in that group.
$claim = $store->stake_claim( 10, null, array(), $group1 );
$this->assertEquals( 1, count( $claim->get_actions() ) );
$this->assertTrue( in_array( $action1, $claim->get_actions() ) );
$store->release_claim( $claim );
}
public function test_claim_actions_by_hook_and_group() {
$hook1 = __FUNCTION__ . '_hook_1';
$hook2 = __FUNCTION__ . '_hook_2';
$hook3 = __FUNCTION__ . '_hook_3';
$group1 = 'group_' . md5( rand() );
$group2 = 'group_' . md5( rand() );
$store = new ActionScheduler_wpPostStore();
$schedule = new ActionScheduler_SimpleSchedule( as_get_datetime_object( '-1 hour' ) );
$action1 = $store->save_action( new ActionScheduler_Action( $hook1, array(), $schedule, $group1 ) );
$action2 = $store->save_action( new ActionScheduler_Action( $hook2, array(), $schedule ) );
$action3 = $store->save_action( new ActionScheduler_Action( $hook3, array(), $schedule, $group2 ) );
// Claiming no hooks or group should include all actions.
$claim = $store->stake_claim( 10 );
$this->assertEquals( 3, count( $claim->get_actions() ) );
$this->assertTrue( in_array( $action1, $claim->get_actions() ) );
$this->assertTrue( in_array( $action2, $claim->get_actions() ) );
$store->release_claim( $claim );
// Claiming a group and hook should claim only actions in that group.
$claim = $store->stake_claim( 10, null, array( $hook1 ), $group1 );
$this->assertEquals( 1, count( $claim->get_actions() ) );
$this->assertTrue( in_array( $action1, $claim->get_actions() ) );
$store->release_claim( $claim );
// Claiming a group and hook should claim only actions with that hook in that group.
$claim = $store->stake_claim( 10, null, array( $hook2 ), $group1 );
$this->assertEquals( 0, count( $claim->get_actions() ) );
$this->assertFalse( in_array( $action1, $claim->get_actions() ) );
$this->assertFalse( in_array( $action2, $claim->get_actions() ) );
$store->release_claim( $claim );
// Claiming a group and hook should claim only actions with that hook in that group.
$claim = $store->stake_claim( 10, null, array( $hook1, $hook2 ), $group2 );
$this->assertEquals( 0, count( $claim->get_actions() ) );
$this->assertFalse( in_array( $action1, $claim->get_actions() ) );
$this->assertFalse( in_array( $action2, $claim->get_actions() ) );
$store->release_claim( $claim );
}
}

View File

@ -1,185 +0,0 @@
<?php
/**
* Class ActionScheduler_wpCommentLogger_Test
* @package test_cases\logging
*/
class ActionScheduler_wpCommentLogger_Test extends ActionScheduler_UnitTestCase {
public function test_default_logger() {
$logger = ActionScheduler::logger();
$this->assertInstanceOf( 'ActionScheduler_Logger', $logger );
$this->assertInstanceOf( 'ActionScheduler_wpCommentLogger', $logger );
}
public function test_add_log_entry() {
$action_id = as_schedule_single_action( time(), 'a hook' );
$logger = ActionScheduler::logger();
$message = 'Logging that something happened';
$log_id = $logger->log( $action_id, $message );
$entry = $logger->get_entry( $log_id );
$this->assertEquals( $action_id, $entry->get_action_id() );
$this->assertEquals( $message, $entry->get_message() );
}
public function test_add_log_datetime() {
$action_id = as_schedule_single_action( time(), 'a hook' );
$logger = ActionScheduler::logger();
$message = 'Logging that something happened';
$date = new DateTime( 'now', new DateTimeZone( 'UTC' ) );
$log_id = $logger->log( $action_id, $message, $date );
$entry = $logger->get_entry( $log_id );
$this->assertEquals( $action_id, $entry->get_action_id() );
$this->assertEquals( $message, $entry->get_message() );
$date = new ActionScheduler_DateTime( 'now', new DateTimeZone( 'UTC' ) );
$log_id = $logger->log( $action_id, $message, $date );
$entry = $logger->get_entry( $log_id );
$this->assertEquals( $action_id, $entry->get_action_id() );
$this->assertEquals( $message, $entry->get_message() );
}
public function test_null_log_entry() {
$logger = ActionScheduler::logger();
$entry = $logger->get_entry( 1 );
$this->assertEquals( '', $entry->get_action_id() );
$this->assertEquals( '', $entry->get_message() );
}
public function test_erroneous_entry_id() {
$comment = wp_insert_comment(array(
'comment_post_ID' => 1,
'comment_author' => 'test',
'comment_content' => 'this is not a log entry',
));
$logger = ActionScheduler::logger();
$entry = $logger->get_entry( $comment );
$this->assertEquals( '', $entry->get_action_id() );
$this->assertEquals( '', $entry->get_message() );
}
public function test_storage_comments() {
$action_id = as_schedule_single_action( time(), 'a hook' );
$logger = ActionScheduler::logger();
$logs = $logger->get_logs( $action_id );
$expected = new ActionScheduler_LogEntry( $action_id, 'action created' );
$this->assertTrue( in_array( $this->log_entry_to_array( $expected ) , $this->log_entry_to_array( $logs ) ) );
}
protected function log_entry_to_array( $logs ) {
if ( $logs instanceof ActionScheduler_LogEntry ) {
return array( 'action_id' => $logs->get_action_id(), 'message' => $logs->get_message() );
}
foreach ( $logs as $id => $log) {
$logs[ $id ] = array( 'action_id' => $log->get_action_id(), 'message' => $log->get_message() );
}
return $logs;
}
public function test_execution_comments() {
$action_id = as_schedule_single_action( time(), 'a hook' );
$logger = ActionScheduler::logger();
$started = new ActionScheduler_LogEntry( $action_id, 'action started' );
$finished = new ActionScheduler_LogEntry( $action_id, 'action complete' );
$runner = new ActionScheduler_QueueRunner();
$runner->run();
$logs = $logger->get_logs( $action_id );
$this->assertTrue( in_array( $this->log_entry_to_array( $started ), $this->log_entry_to_array( $logs ) ) );
$this->assertTrue( in_array( $this->log_entry_to_array( $finished ), $this->log_entry_to_array( $logs ) ) );
}
public function test_failed_execution_comments() {
$hook = md5(rand());
add_action( $hook, array( $this, '_a_hook_callback_that_throws_an_exception' ) );
$action_id = as_schedule_single_action( time(), $hook );
$logger = ActionScheduler::logger();
$started = new ActionScheduler_LogEntry( $action_id, 'action started' );
$finished = new ActionScheduler_LogEntry( $action_id, 'action complete' );
$failed = new ActionScheduler_LogEntry( $action_id, 'action failed: Execution failed' );
$runner = new ActionScheduler_QueueRunner();
$runner->run();
$logs = $logger->get_logs( $action_id );
$this->assertTrue( in_array( $this->log_entry_to_array( $started ), $this->log_entry_to_array( $logs ) ) );
$this->assertFalse( in_array( $this->log_entry_to_array( $finished ), $this->log_entry_to_array( $logs ) ) );
$this->assertTrue( in_array( $this->log_entry_to_array( $failed ), $this->log_entry_to_array( $logs ) ) );
}
public function test_fatal_error_comments() {
$hook = md5(rand());
$action_id = as_schedule_single_action( time(), $hook );
$logger = ActionScheduler::logger();
do_action( 'action_scheduler_unexpected_shutdown', $action_id, array(
'type' => E_ERROR,
'message' => 'Test error',
'file' => __FILE__,
'line' => __LINE__,
));
$logs = $logger->get_logs( $action_id );
$found_log = FALSE;
foreach ( $logs as $l ) {
if ( strpos( $l->get_message(), 'unexpected shutdown' ) === 0 ) {
$found_log = TRUE;
}
}
$this->assertTrue( $found_log, 'Unexpected shutdown log not found' );
}
public function test_canceled_action_comments() {
$action_id = as_schedule_single_action( time(), 'a hook' );
as_unschedule_action( 'a hook' );
$logger = ActionScheduler::logger();
$logs = $logger->get_logs( $action_id );
$expected = new ActionScheduler_LogEntry( $action_id, 'action canceled' );
$this->assertTrue( in_array( $this->log_entry_to_array( $expected ), $this->log_entry_to_array( $logs ) ) );
}
public function _a_hook_callback_that_throws_an_exception() {
throw new RuntimeException('Execution failed');
}
public function test_filtering_of_get_comments() {
$post_id = $this->factory->post->create_object(array(
'post_title' => __FUNCTION__,
));
$comment_id = $this->factory->comment->create_object(array(
'comment_post_ID' => $post_id,
'comment_author' => __CLASS__,
'comment_content' => __FUNCTION__,
));
// Verify that we're getting the expected comment before we add logging comments
$comments = get_comments();
$this->assertCount( 1, $comments );
$this->assertEquals( $comment_id, $comments[0]->comment_ID );
$action_id = as_schedule_single_action( time(), 'a hook' );
$logger = ActionScheduler::logger();
$message = 'Logging that something happened';
$log_id = $logger->log( $action_id, $message );
// Verify that logging comments are excluded from general comment queries
$comments = get_comments();
$this->assertCount( 1, $comments );
$this->assertEquals( $comment_id, $comments[0]->comment_ID );
// Verify that logging comments are returned when asking for them specifically
$comments = get_comments(array(
'type' => ActionScheduler_wpCommentLogger::TYPE,
));
// Expecting two: one when the action is created, another when we added our custom log
$this->assertCount( 2, $comments );
$this->assertContains( $log_id, wp_list_pluck($comments, 'comment_ID'));
}
}

View File

@ -1,222 +0,0 @@
<?php
/**
* Class procedural_api_Test
*/
class procedural_api_Test extends ActionScheduler_UnitTestCase {
public function test_schedule_action() {
$time = time();
$hook = md5(rand());
$action_id = as_schedule_single_action( $time, $hook );
$store = ActionScheduler::store();
$action = $store->fetch_action($action_id);
$this->assertEquals( $time, $action->get_schedule()->next()->getTimestamp() );
$this->assertEquals( $hook, $action->get_hook() );
}
public function test_recurring_action() {
$time = time();
$hook = md5(rand());
$action_id = as_schedule_recurring_action( $time, HOUR_IN_SECONDS, $hook );
$store = ActionScheduler::store();
$action = $store->fetch_action($action_id);
$this->assertEquals( $time, $action->get_schedule()->next()->getTimestamp() );
$this->assertEquals( $time + HOUR_IN_SECONDS + 2, $action->get_schedule()->next(as_get_datetime_object($time + 2))->getTimestamp());
$this->assertEquals( $hook, $action->get_hook() );
}
public function test_cron_schedule() {
$time = as_get_datetime_object('2014-01-01');
$hook = md5(rand());
$action_id = as_schedule_cron_action( $time->getTimestamp(), '0 0 10 10 *', $hook );
$store = ActionScheduler::store();
$action = $store->fetch_action($action_id);
$expected_date = as_get_datetime_object('2014-10-10');
$this->assertEquals( $expected_date->getTimestamp(), $action->get_schedule()->next()->getTimestamp() );
$this->assertEquals( $hook, $action->get_hook() );
}
public function test_get_next() {
$time = as_get_datetime_object('tomorrow');
$hook = md5(rand());
as_schedule_recurring_action( $time->getTimestamp(), HOUR_IN_SECONDS, $hook );
$next = as_next_scheduled_action( $hook );
$this->assertEquals( $time->getTimestamp(), $next );
}
public function provider_time_hook_args_group() {
$time = time() + 60 * 2;
$hook = md5( rand() );
$args = array( rand(), rand() );
$group = 'test_group';
return array(
// Test with no args or group
array(
'time' => $time,
'hook' => $hook,
'args' => array(),
'group' => '',
),
// Test with args but no group
array(
'time' => $time,
'hook' => $hook,
'args' => $args,
'group' => '',
),
// Test with group but no args
array(
'time' => $time,
'hook' => $hook,
'args' => array(),
'group' => $group,
),
// Test with args & group
array(
'time' => $time,
'hook' => $hook,
'args' => $args,
'group' => $group,
),
);
}
/**
* @dataProvider provider_time_hook_args_group
*/
public function test_unschedule( $time, $hook, $args, $group ) {
$action_id_unscheduled = as_schedule_single_action( $time, $hook, $args, $group );
$action_scheduled_time = $time + 1;
$action_id_scheduled = as_schedule_single_action( $action_scheduled_time, $hook, $args, $group );
as_unschedule_action( $hook, $args, $group );
$next = as_next_scheduled_action( $hook, $args, $group );
$this->assertEquals( $action_scheduled_time, $next );
$store = ActionScheduler::store();
$unscheduled_action = $store->fetch_action( $action_id_unscheduled );
// Make sure the next scheduled action is unscheduled
$this->assertEquals( $hook, $unscheduled_action->get_hook() );
$this->assertNull( $unscheduled_action->get_schedule()->next() );
// Make sure other scheduled actions are not unscheduled
$scheduled_action = $store->fetch_action( $action_id_scheduled );
$this->assertEquals( $hook, $scheduled_action->get_hook() );
$this->assertEquals( $action_scheduled_time, $scheduled_action->get_schedule()->next()->getTimestamp() );
}
/**
* @dataProvider provider_time_hook_args_group
*/
public function test_unschedule_all( $time, $hook, $args, $group ) {
$hook = md5( $hook );
$action_ids = array();
for ( $i = 0; $i < 3; $i++ ) {
$action_ids[] = as_schedule_single_action( $time, $hook, $args, $group );
}
as_unschedule_all_actions( $hook, $args, $group );
$next = as_next_scheduled_action( $hook );
$this->assertFalse($next);
$store = ActionScheduler::store();
foreach ( $action_ids as $action_id ) {
$action = $store->fetch_action($action_id);
$this->assertNull($action->get_schedule()->next());
$this->assertEquals($hook, $action->get_hook() );
}
}
public function test_as_get_datetime_object_default() {
$utc_now = new ActionScheduler_DateTime(null, new DateTimeZone('UTC'));
$as_now = as_get_datetime_object();
// Don't want to use 'U' as timestamps will always be in UTC
$this->assertEquals($utc_now->format('Y-m-d H:i:s'),$as_now->format('Y-m-d H:i:s'));
}
public function test_as_get_datetime_object_relative() {
$utc_tomorrow = new ActionScheduler_DateTime('tomorrow', new DateTimeZone('UTC'));
$as_tomorrow = as_get_datetime_object('tomorrow');
$this->assertEquals($utc_tomorrow->format('Y-m-d H:i:s'),$as_tomorrow->format('Y-m-d H:i:s'));
$utc_tomorrow = new ActionScheduler_DateTime('yesterday', new DateTimeZone('UTC'));
$as_tomorrow = as_get_datetime_object('yesterday');
$this->assertEquals($utc_tomorrow->format('Y-m-d H:i:s'),$as_tomorrow->format('Y-m-d H:i:s'));
}
public function test_as_get_datetime_object_fixed() {
$utc_tomorrow = new ActionScheduler_DateTime('29 February 2016', new DateTimeZone('UTC'));
$as_tomorrow = as_get_datetime_object('29 February 2016');
$this->assertEquals($utc_tomorrow->format('Y-m-d H:i:s'),$as_tomorrow->format('Y-m-d H:i:s'));
$utc_tomorrow = new ActionScheduler_DateTime('1st January 2024', new DateTimeZone('UTC'));
$as_tomorrow = as_get_datetime_object('1st January 2024');
$this->assertEquals($utc_tomorrow->format('Y-m-d H:i:s'),$as_tomorrow->format('Y-m-d H:i:s'));
}
public function test_as_get_datetime_object_timezone() {
$timezone_au = 'Australia/Brisbane';
$timezone_default = date_default_timezone_get();
date_default_timezone_set( $timezone_au );
$au_now = new ActionScheduler_DateTime(null);
$as_now = as_get_datetime_object();
// Make sure they're for the same time
$this->assertEquals($au_now->getTimestamp(),$as_now->getTimestamp());
// But not in the same timezone, as $as_now should be using UTC
$this->assertNotEquals($au_now->format('Y-m-d H:i:s'),$as_now->format('Y-m-d H:i:s'));
$au_now = new ActionScheduler_DateTime(null);
$as_au_now = as_get_datetime_object();
$this->assertEquals($au_now->getTimestamp(),$as_now->getTimestamp());
// But not in the same timezone, as $as_now should be using UTC
$this->assertNotEquals($au_now->format('Y-m-d H:i:s'),$as_now->format('Y-m-d H:i:s'));
// Just in cases
date_default_timezone_set( $timezone_default );
}
public function test_as_get_datetime_object_type() {
$f = 'Y-m-d H:i:s';
$now = as_get_datetime_object();
$this->assertInstanceOf( 'ActionScheduler_DateTime', $now );
$dateTime = new DateTime( 'now', new DateTimeZone( 'UTC' ) );
$asDateTime = as_get_datetime_object( $dateTime );
$this->assertEquals( $dateTime->format( $f ), $asDateTime->format( $f ) );
}
}

View File

@ -1,100 +0,0 @@
<?php
/**
* Class as_get_scheduled_actions_Test
*/
class as_get_scheduled_actions_Test extends ActionScheduler_UnitTestCase {
private $hooks = array();
private $args = array();
private $groups = array();
public function setUp() {
parent::setUp();
$store = ActionScheduler::store();
for ( $i = 0 ; $i < 10 ; $i++ ) {
$this->hooks[$i] = md5(rand());
$this->args[$i] = md5(rand());
$this->groups[$i] = md5(rand());
}
for ( $i = 0 ; $i < 10 ; $i++ ) {
for ( $j = 0 ; $j < 10 ; $j++ ) {
$schedule = new ActionScheduler_SimpleSchedule( as_get_datetime_object( $j - 3 . 'days') );
$group = $this->groups[ ( $i + $j ) % 10 ];
$action = new ActionScheduler_Action( $this->hooks[$i], array($this->args[$j]), $schedule, $group );
$store->save_action( $action );
}
}
}
public function test_date_queries() {
$actions = as_get_scheduled_actions(array(
'date' => as_get_datetime_object(gmdate('Y-m-d 00:00:00')),
'per_page' => -1,
), 'ids');
$this->assertCount(30, $actions);
$actions = as_get_scheduled_actions(array(
'date' => as_get_datetime_object(gmdate('Y-m-d 00:00:00')),
'date_compare' => '>=',
'per_page' => -1,
), 'ids');
$this->assertCount(70, $actions);
}
public function test_hook_queries() {
$actions = as_get_scheduled_actions(array(
'hook' => $this->hooks[2],
'per_page' => -1,
), 'ids');
$this->assertCount(10, $actions);
$actions = as_get_scheduled_actions(array(
'hook' => $this->hooks[2],
'date' => as_get_datetime_object(gmdate('Y-m-d 00:00:00')),
'per_page' => -1,
), 'ids');
$this->assertCount(3, $actions);
}
public function test_args_queries() {
$actions = as_get_scheduled_actions(array(
'args' => array($this->args[5]),
'per_page' => -1,
), 'ids');
$this->assertCount(10, $actions);
$actions = as_get_scheduled_actions(array(
'args' => array($this->args[5]),
'hook' => $this->hooks[3],
'per_page' => -1,
), 'ids');
$this->assertCount(1, $actions);
$actions = as_get_scheduled_actions(array(
'args' => array($this->args[5]),
'hook' => $this->hooks[3],
'date' => as_get_datetime_object(gmdate('Y-m-d 00:00:00')),
'per_page' => -1,
), 'ids');
$this->assertCount(0, $actions);
}
public function test_group_queries() {
$actions = as_get_scheduled_actions(array(
'group' => $this->groups[1],
'per_page' => -1,
), 'ids');
$this->assertCount(10, $actions);
$actions = as_get_scheduled_actions(array(
'group' => $this->groups[1],
'hook' => $this->hooks[9],
'per_page' => -1,
), 'ids');
$this->assertCount(1, $actions);
}
}

View File

@ -1,151 +0,0 @@
<?php
/**
* Class ActionScheduler_QueueCleaner_Test
*/
class ActionScheduler_QueueCleaner_Test extends ActionScheduler_UnitTestCase {
public function test_delete_old_actions() {
$store = ActionScheduler::store();
$runner = new ActionScheduler_QueueRunner( $store );
$random = md5(rand());
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('1 day ago'));
$created_actions = array();
for ( $i = 0 ; $i < 5 ; $i++ ) {
$action = new ActionScheduler_Action( $random, array($random), $schedule );
$created_actions[] = $store->save_action( $action );
}
$runner->run();
add_filter( 'action_scheduler_retention_period', '__return_zero' ); // delete any finished job
$cleaner = new ActionScheduler_QueueCleaner( $store );
$cleaner->delete_old_actions();
remove_filter( 'action_scheduler_retention_period', '__return_zero' );
foreach ( $created_actions as $action_id ) {
$action = $store->fetch_action($action_id);
$this->assertFalse($action->is_finished()); // it's a NullAction
}
}
public function test_delete_canceled_actions() {
$store = ActionScheduler::store();
$random = md5(rand());
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('1 day ago'));
$created_actions = array();
for ( $i = 0 ; $i < 5 ; $i++ ) {
$action = new ActionScheduler_Action( $random, array($random), $schedule );
$action_id = $store->save_action( $action );
$store->cancel_action( $action_id );
$created_actions[] = $action_id;
}
// track the actions that are deleted
$mock_action = new MockAction();
add_action( 'action_scheduler_deleted_action', array( $mock_action, 'action' ), 10, 1 );
add_filter( 'action_scheduler_retention_period', '__return_zero' ); // delete any finished job
$cleaner = new ActionScheduler_QueueCleaner( $store );
$cleaner->delete_old_actions();
remove_filter( 'action_scheduler_retention_period', '__return_zero' );
remove_action( 'action_scheduler_deleted_action', array( $mock_action, 'action' ), 10 );
$deleted_actions = array_map( 'reset', $mock_action->get_args() );
$this->assertEqualSets( $created_actions, $deleted_actions );
}
public function test_do_not_delete_recent_actions() {
$store = ActionScheduler::store();
$runner = new ActionScheduler_QueueRunner( $store );
$random = md5(rand());
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('1 day ago'));
$created_actions = array();
for ( $i = 0 ; $i < 5 ; $i++ ) {
$action = new ActionScheduler_Action( $random, array($random), $schedule );
$created_actions[] = $store->save_action( $action );
}
$runner->run();
$cleaner = new ActionScheduler_QueueCleaner( $store );
$cleaner->delete_old_actions();
foreach ( $created_actions as $action_id ) {
$action = $store->fetch_action($action_id);
$this->assertTrue($action->is_finished()); // It's a FinishedAction
}
}
public function test_reset_unrun_actions() {
$store = ActionScheduler::store();
$random = md5(rand());
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('1 day ago'));
$created_actions = array();
for ( $i = 0 ; $i < 5 ; $i++ ) {
$action = new ActionScheduler_Action( $random, array($random), $schedule );
$created_actions[] = $store->save_action( $action );
}
$store->stake_claim(10);
// don't actually process the jobs, to simulate a request that timed out
add_filter( 'action_scheduler_timeout_period', '__return_zero' ); // delete any finished job
$cleaner = new ActionScheduler_QueueCleaner( $store );
$cleaner->reset_timeouts();
remove_filter( 'action_scheduler_timeout_period', '__return_zero' );
$claim = $store->stake_claim(10);
$this->assertEqualSets($created_actions, $claim->get_actions());
}
public function test_do_not_reset_failed_action() {
$store = ActionScheduler::store();
$random = md5(rand());
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('1 day ago'));
$created_actions = array();
for ( $i = 0 ; $i < 5 ; $i++ ) {
$action = new ActionScheduler_Action( $random, array($random), $schedule );
$created_actions[] = $store->save_action( $action );
}
$claim = $store->stake_claim(10);
foreach ( $claim->get_actions() as $action_id ) {
// simulate the first action interrupted by an uncatchable fatal error
$store->log_execution( $action_id );
break;
}
add_filter( 'action_scheduler_timeout_period', '__return_zero' ); // delete any finished job
$cleaner = new ActionScheduler_QueueCleaner( $store );
$cleaner->reset_timeouts();
remove_filter( 'action_scheduler_timeout_period', '__return_zero' );
$new_claim = $store->stake_claim(10);
$this->assertCount( 4, $new_claim->get_actions() );
add_filter( 'action_scheduler_failure_period', '__return_zero' );
$cleaner->mark_failures();
remove_filter( 'action_scheduler_failure_period', '__return_zero' );
$failed = $store->query_actions(array('status' => ActionScheduler_Store::STATUS_FAILED));
$this->assertEquals( $created_actions[0], $failed[0] );
$this->assertCount( 1, $failed );
}
}

View File

@ -1,262 +0,0 @@
<?php
/**
* Class ActionScheduler_QueueRunner_Test
* @group runners
*/
class ActionScheduler_QueueRunner_Test extends ActionScheduler_UnitTestCase {
public function test_create_runner() {
$store = ActionScheduler::store();
$runner = new ActionScheduler_QueueRunner( $store );
$actions_run = $runner->run();
$this->assertEquals( 0, $actions_run );
}
public function test_run() {
$store = ActionScheduler::store();
$runner = new ActionScheduler_QueueRunner( $store );
$mock = new MockAction();
$random = md5(rand());
add_action( $random, array( $mock, 'action' ) );
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('1 day ago'));
for ( $i = 0 ; $i < 5 ; $i++ ) {
$action = new ActionScheduler_Action( $random, array($random), $schedule );
$store->save_action( $action );
}
$actions_run = $runner->run();
remove_action( $random, array( $mock, 'action' ) );
$this->assertEquals( 5, $mock->get_call_count() );
$this->assertEquals( 5, $actions_run );
}
public function test_run_with_future_actions() {
$store = ActionScheduler::store();
$runner = new ActionScheduler_QueueRunner( $store );
$mock = new MockAction();
$random = md5(rand());
add_action( $random, array( $mock, 'action' ) );
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('1 day ago'));
for ( $i = 0 ; $i < 3 ; $i++ ) {
$action = new ActionScheduler_Action( $random, array($random), $schedule );
$store->save_action( $action );
}
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('tomorrow'));
for ( $i = 0 ; $i < 3 ; $i++ ) {
$action = new ActionScheduler_Action( $random, array($random), $schedule );
$store->save_action( $action );
}
$actions_run = $runner->run();
remove_action( $random, array( $mock, 'action' ) );
$this->assertEquals( 3, $mock->get_call_count() );
$this->assertEquals( 3, $actions_run );
}
public function test_completed_action_status() {
$store = ActionScheduler::store();
$runner = new ActionScheduler_QueueRunner( $store );
$random = md5(rand());
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('12 hours ago'));
$action = new ActionScheduler_Action( $random, array(), $schedule );
$action_id = $store->save_action( $action );
$runner->run();
$finished_action = $store->fetch_action( $action_id );
$this->assertTrue( $finished_action->is_finished() );
}
public function test_next_instance_of_action() {
$store = ActionScheduler::store();
$runner = new ActionScheduler_QueueRunner( $store );
$random = md5(rand());
$schedule = new ActionScheduler_IntervalSchedule(as_get_datetime_object('12 hours ago'), DAY_IN_SECONDS);
$action = new ActionScheduler_Action( $random, array(), $schedule );
$store->save_action( $action );
$runner->run();
$claim = $store->stake_claim(10, as_get_datetime_object((DAY_IN_SECONDS - 60).' seconds'));
$this->assertCount(0, $claim->get_actions());
$claim = $store->stake_claim(10, as_get_datetime_object(DAY_IN_SECONDS.' seconds'));
$actions = $claim->get_actions();
$this->assertCount(1, $actions);
$action_id = reset($actions);
$new_action = $store->fetch_action($action_id);
$this->assertEquals( $random, $new_action->get_hook() );
$this->assertEquals( $schedule->next(as_get_datetime_object())->getTimestamp(), $new_action->get_schedule()->next(as_get_datetime_object())->getTimestamp() );
}
public function test_hooked_into_wp_cron() {
$next = wp_next_scheduled( ActionScheduler_QueueRunner::WP_CRON_HOOK );
$this->assertNotEmpty($next);
}
public function test_batch_count_limit() {
$store = ActionScheduler::store();
$runner = new ActionScheduler_QueueRunner( $store );
$mock = new MockAction();
$random = md5(rand());
add_action( $random, array( $mock, 'action' ) );
$schedule = new ActionScheduler_SimpleSchedule(new ActionScheduler_DateTime('1 day ago'));
for ( $i = 0 ; $i < 30 ; $i++ ) {
$action = new ActionScheduler_Action( $random, array($random), $schedule );
$store->save_action( $action );
}
$claims = array();
for ( $i = 0 ; $i < 5 ; $i++ ) {
$claims[] = $store->stake_claim( 5 );
}
$actions_run = $runner->run();
$this->assertEquals( 0, $mock->get_call_count() );
$this->assertEquals( 0, $actions_run );
$first = reset($claims);
$store->release_claim( $first );
$actions_run = $runner->run();
$this->assertEquals( 10, $mock->get_call_count() );
$this->assertEquals( 10, $actions_run );
remove_action( $random, array( $mock, 'action' ) );
}
public function test_changing_batch_count_limit() {
$store = ActionScheduler::store();
$runner = new ActionScheduler_QueueRunner( $store );
$random = md5(rand());
$schedule = new ActionScheduler_SimpleSchedule(new ActionScheduler_DateTime('1 day ago'));
for ( $i = 0 ; $i < 30 ; $i++ ) {
$action = new ActionScheduler_Action( $random, array($random), $schedule );
$store->save_action( $action );
}
$claims = array();
for ( $i = 0 ; $i < 5 ; $i++ ) {
$claims[] = $store->stake_claim( 5 );
}
$mock1 = new MockAction();
add_action( $random, array( $mock1, 'action' ) );
$actions_run = $runner->run();
remove_action( $random, array( $mock1, 'action' ) );
$this->assertEquals( 0, $mock1->get_call_count() );
$this->assertEquals( 0, $actions_run );
add_filter( 'action_scheduler_queue_runner_concurrent_batches', array( $this, 'return_6' ) );
$mock2 = new MockAction();
add_action( $random, array( $mock2, 'action' ) );
$actions_run = $runner->run();
remove_action( $random, array( $mock2, 'action' ) );
$this->assertEquals( 5, $mock2->get_call_count() );
$this->assertEquals( 5, $actions_run );
remove_filter( 'action_scheduler_queue_runner_concurrent_batches', array( $this, 'return_6' ) );
for ( $i = 0 ; $i < 5 ; $i++ ) { // to make up for the actions we just processed
$action = new ActionScheduler_Action( $random, array($random), $schedule );
$store->save_action( $action );
}
$mock3 = new MockAction();
add_action( $random, array( $mock3, 'action' ) );
$actions_run = $runner->run();
remove_action( $random, array( $mock3, 'action' ) );
$this->assertEquals( 0, $mock3->get_call_count() );
$this->assertEquals( 0, $actions_run );
remove_filter( 'action_scheduler_queue_runner_concurrent_batches', array( $this, 'return_6' ) );
}
public function return_6() {
return 6;
}
public function test_store_fetch_action_failure_schedule_next_instance() {
$random = md5( rand() );
$schedule = new ActionScheduler_IntervalSchedule( as_get_datetime_object( '12 hours ago' ), DAY_IN_SECONDS );
$action = new ActionScheduler_Action( $random, array(), $schedule );
$action_id = ActionScheduler::store()->save_action( $action );
// Set up a mock store that will throw an exception when fetching actions.
$store = $this
->getMockBuilder( 'ActionScheduler_wpPostStore' )
->setMethods( array( 'fetch_action' ) )
->getMock();
$store
->method( 'fetch_action' )
->with( $action_id )
->will( $this->throwException( new Exception() ) );
// Set up a mock queue runner to verify that schedule_next_instance()
// isn't called for an undefined $action.
$runner = $this
->getMockBuilder( 'ActionScheduler_QueueRunner' )
->setConstructorArgs( array( $store ) )
->setMethods( array( 'schedule_next_instance' ) )
->getMock();
$runner
->expects( $this->never() )
->method( 'schedule_next_instance' );
$runner->run();
// Set up a mock store that will throw an exception when fetching actions.
$store2 = $this
->getMockBuilder( 'ActionScheduler_wpPostStore' )
->setMethods( array( 'fetch_action' ) )
->getMock();
$store2
->method( 'fetch_action' )
->with( $action_id )
->willReturn( null );
// Set up a mock queue runner to verify that schedule_next_instance()
// isn't called for an undefined $action.
$runner2 = $this
->getMockBuilder( 'ActionScheduler_QueueRunner' )
->setConstructorArgs( array( $store ) )
->setMethods( array( 'schedule_next_instance' ) )
->getMock();
$runner2
->expects( $this->never() )
->method( 'schedule_next_instance' );
$runner2->run();
}
}

View File

@ -1,45 +0,0 @@
<?php
/**
* Class ActionScheduler_CronSchedule_Test
* @group schedules
*/
class ActionScheduler_CronSchedule_Test extends ActionScheduler_UnitTestCase {
public function test_creation() {
$time = as_get_datetime_object('tomorrow');
$cron = CronExpression::factory('@daily');
$schedule = new ActionScheduler_CronSchedule(as_get_datetime_object(), $cron);
$this->assertEquals( $time, $schedule->next() );
}
public function test_next() {
$time = as_get_datetime_object('2013-06-14');
$cron = CronExpression::factory('@daily');
$schedule = new ActionScheduler_CronSchedule($time, $cron);
$this->assertEquals( as_get_datetime_object('tomorrow'), $schedule->next( as_get_datetime_object() ) );
}
public function test_is_recurring() {
$schedule = new ActionScheduler_CronSchedule(as_get_datetime_object('2013-06-14'), CronExpression::factory('@daily'));
$this->assertTrue( $schedule->is_recurring() );
}
public function test_cron_format() {
$time = as_get_datetime_object('2014-01-01');
$cron = CronExpression::factory('0 0 10 10 *');
$schedule = new ActionScheduler_CronSchedule($time, $cron);
$this->assertEquals( as_get_datetime_object('2014-10-10'), $schedule->next() );
$cron = CronExpression::factory('0 0 L 1/2 *');
$schedule = new ActionScheduler_CronSchedule($time, $cron);
$this->assertEquals( as_get_datetime_object('2014-01-31'), $schedule->next() );
$this->assertEquals( as_get_datetime_object('2014-07-31'), $schedule->next( as_get_datetime_object('2014-06-01') ) );
$this->assertEquals( as_get_datetime_object('2028-11-30'), $schedule->next( as_get_datetime_object('2028-11-01') ) );
$cron = CronExpression::factory('30 14 * * MON#3 *');
$schedule = new ActionScheduler_CronSchedule($time, $cron);
$this->assertEquals( as_get_datetime_object('2014-01-20 14:30:00'), $schedule->next() );
$this->assertEquals( as_get_datetime_object('2014-05-19 14:30:00'), $schedule->next( as_get_datetime_object('2014-05-01') ) );
}
}

View File

@ -1,28 +0,0 @@
<?php
/**
* Class ActionScheduler_IntervalSchedule_Test
* @group schedules
*/
class ActionScheduler_IntervalSchedule_Test extends ActionScheduler_UnitTestCase {
public function test_creation() {
$time = as_get_datetime_object();
$schedule = new ActionScheduler_IntervalSchedule($time, HOUR_IN_SECONDS);
$this->assertEquals( $time, $schedule->next() );
}
public function test_next() {
$now = time();
$start = $now - 30;
$schedule = new ActionScheduler_IntervalSchedule( as_get_datetime_object("@$start"), MINUTE_IN_SECONDS );
$this->assertEquals( $start, $schedule->next()->getTimestamp() );
$this->assertEquals( $now + MINUTE_IN_SECONDS, $schedule->next(as_get_datetime_object())->getTimestamp() );
$this->assertEquals( $start, $schedule->next(as_get_datetime_object("@$start"))->getTimestamp() );
}
public function test_is_recurring() {
$start = time() - 30;
$schedule = new ActionScheduler_IntervalSchedule( as_get_datetime_object("@$start"), MINUTE_IN_SECONDS );
$this->assertTrue( $schedule->is_recurring() );
}
}

View File

@ -1,18 +0,0 @@
<?php
/**
* Class ActionScheduler_NullSchedule_Test
* @group schedules
*/
class ActionScheduler_NullSchedule_Test extends ActionScheduler_UnitTestCase {
public function test_null_schedule() {
$schedule = new ActionScheduler_NullSchedule();
$this->assertNull( $schedule->next() );
}
public function test_is_recurring() {
$schedule = new ActionScheduler_NullSchedule();
$this->assertFalse( $schedule->is_recurring() );
}
}

View File

@ -1,37 +0,0 @@
<?php
/**
* Class ActionScheduler_SimpleSchedule_Test
* @group schedules
*/
class ActionScheduler_SimpleSchedule_Test extends ActionScheduler_UnitTestCase {
public function test_creation() {
$time = as_get_datetime_object();
$schedule = new ActionScheduler_SimpleSchedule($time);
$this->assertEquals( $time, $schedule->next() );
}
public function test_past_date() {
$time = as_get_datetime_object('-1 day');
$schedule = new ActionScheduler_SimpleSchedule($time);
$this->assertEquals( $time, $schedule->next() );
}
public function test_future_date() {
$time = as_get_datetime_object('+1 day');
$schedule = new ActionScheduler_SimpleSchedule($time);
$this->assertEquals( $time, $schedule->next() );
}
public function test_grace_period_for_next() {
$time = as_get_datetime_object('3 seconds ago');
$schedule = new ActionScheduler_SimpleSchedule($time);
$this->assertEquals( $time, $schedule->next() );
}
public function test_is_recurring() {
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('+1 day'));
$this->assertFalse( $schedule->is_recurring() );
}
}

View File

@ -1,43 +0,0 @@
<?php
/**
* Class ActionScheduler_Versions_Test
*/
class ActionScheduler_Versions_Test extends ActionScheduler_UnitTestCase {
public function test_register_version() {
$versions = new ActionScheduler_Versions();
$versions->register('1.0-dev', 'callback_1_dot_0_dev');
$versions->register('1.0', 'callback_1_dot_0');
$registered = $versions->get_versions();
$this->assertArrayHasKey( '1.0-dev', $registered );
$this->assertArrayHasKey( '1.0', $registered );
$this->assertCount( 2, $registered );
$this->assertEquals( 'callback_1_dot_0_dev', $registered['1.0-dev'] );
}
public function test_duplicate_version() {
$versions = new ActionScheduler_Versions();
$versions->register('1.0', 'callback_1_dot_0_a');
$versions->register('1.0', 'callback_1_dot_0_b');
$registered = $versions->get_versions();
$this->assertArrayHasKey( '1.0', $registered );
$this->assertCount( 1, $registered );
}
public function test_latest_version() {
$versions = new ActionScheduler_Versions();
$this->assertEquals('__return_null', $versions->latest_version_callback() );
$versions->register('1.2', 'callback_1_dot_2');
$versions->register('1.3', 'callback_1_dot_3');
$versions->register('1.0', 'callback_1_dot_0');
$this->assertEquals( '1.3', $versions->latest_version() );
$this->assertEquals( 'callback_1_dot_3', $versions->latest_version_callback() );
}
}

View File

@ -1,38 +0,0 @@
#!/bin/sh
# WordPress test setup script for Travis CI
#
# Author: Benjamin J. Balter ( ben@balter.com | ben.balter.com )
# License: GPL3
export WP_CORE_DIR=/tmp/wordpress
export WP_TESTS_DIR=/tmp/wordpress-tests/tests/phpunit
if [[ "$1" = "5.6" || "$1" > "5.6" ]]
then
wget -c https://phar.phpunit.de/phpunit-5.7.phar
chmod +x phpunit-5.7.phar
mv phpunit-5.7.phar `which phpunit`
fi
plugin_slug=$(basename $(pwd))
plugin_dir=$WP_CORE_DIR/wp-content/plugins/$plugin_slug
# Init database
mysql -e 'CREATE DATABASE wordpress_test;' -uroot
# Grab specified version of WordPress from github
wget -nv -O /tmp/wordpress.tar.gz https://github.com/WordPress/WordPress/tarball/$WP_VERSION
mkdir -p $WP_CORE_DIR
tar --strip-components=1 -zxmf /tmp/wordpress.tar.gz -C $WP_CORE_DIR
# Grab testing framework
svn co --quiet https://develop.svn.wordpress.org/tags/$WP_VERSION/ /tmp/wordpress-tests
# Put various components in proper folders
cp tests/travis/wp-tests-config.php $WP_TESTS_DIR/wp-tests-config.php
cd ..
mv $plugin_slug $plugin_dir
cd $plugin_dir

View File

@ -1,38 +0,0 @@
<?php
/* Path to the WordPress codebase you'd like to test. Add a backslash in the end. */
define( 'ABSPATH', getenv( 'WP_CORE_DIR' ) . '/' );
// Test with multisite enabled
define( 'WP_TESTS_MULTISITE', (bool) getenv( 'WP_MULTISITE' ) );
// Force known bugs
// define( 'WP_TESTS_FORCE_KNOWN_BUGS', true );
// Test with WordPress debug mode on
define( 'WP_DEBUG', true );
// ** MySQL settings ** //
// This configuration file will be used by the copy of WordPress being tested.
// wordpress/wp-config.php will be ignored.
// WARNING WARNING WARNING!
// These tests will DROP ALL TABLES in the database with the prefix named below.
// DO NOT use a production database or one that is shared with something else.
define( 'DB_NAME', 'wordpress_test' );
define( 'DB_USER', 'root' );
define( 'DB_PASSWORD', '' );
define( 'DB_HOST', 'localhost' );
define( 'DB_CHARSET', 'utf8' );
define( 'DB_COLLATE', '' );
define( 'WP_TESTS_DOMAIN', 'example.org' );
define( 'WP_TESTS_EMAIL', 'admin@example.org' );
define( 'WP_TESTS_TITLE', 'Test Blog' );
define( 'WP_PHP_BINARY', 'php' );
define( 'WPLANG', '' );
$table_prefix = 'wptests_';