How to make a cronjob type plugin

Hi i am new on wordpress and has been given a task to make such a script that will fetch posts by categories and shoot email to subscribers.

The table structure for subscriber is below

Subscriber Id - primary key
Subscriber email - varchar
Category Id - int

Now the task is to fetch post for last week for each category that exists in above table an send a newsletter to the respective subscribers each monday automatically.

I have an idea how to fetch post i will probably do it with get_post() method but i’m not sure how will i do it. Should i made a plugin? If yes, then can a plugin file be run like a cronjob ? Or if there is any other good approach please advice .


Solutions Collecting From Web of "How to make a cronjob type plugin"

Yes, you can make a plugin. Following is the way to add cron job functionality in WordPress plugin.

However, please note that this does not provide a real (system based) cron. It requires at least someone to visit your site, so that the functions keep on executing periodically.

WordPress already has a cron style mechanism, wp_cron

if ( ! wp_next_scheduled( 'my_task_hook' ) ) {
    wp_schedule_event( time(), 'hourly', 'my_task_hook' );

add_action( 'my_task_hook', 'my_task_function' );

function my_task_function() {
    // do something 

Ofcourse, what you do when the cron job fires is up to you. Your stated use for this is off topic here.

A sidenote

WP Cron is checked when a user visits your site. If you have a 5 minute cron job, but nobody visits for 2 hours, that’s 2 hours during which nothing happens. It also executes after 5 minutes, not on 5 minutes. So if it has been 5 or more minutes since the last time it ran, it will run. Because of this, do not expect it to run at 1:00 on the dot.

This is because WordPress is ran on a wide variety of systems, and there’s no reliable 100% automatic way to schedule a cron job from PHP on all environments.

You can make wp-cron faster and reliable however by having an actual cronjob ping /wp-cron.php