How to Set Up a Cron Job with Twitter API

Twitter is one of the places where the news is leaked as and once it happens.

You don’t have to look into any big news sites and search for the news whereas you can look on your stream with a niche pile of followers  or the simple way is to click at the Discover button at the top of your twitter to make sure you get the news heading.

Obviously you can’t be online all the time in any social media., you gotta sleep at least 5 hours  a day though.

I seem to speak AWOL if I continue to write about twitter. You can still confuse your followers that you’re online all the time with some amount of php knowledge and Linux command knowledge.

There are many web apps as well as mobile apps that is used to schedule tweets given the date and time. But still you might be curious to know being a programmer or a developer why don’t I create my own cron job to tweet on twitter.

Coming to the post, we’re going to see how to write a cron job with twitter assuming you’ve a hosting service provider (Linux).

You can get the code from my GitHub Repository .- tweet-cron-job-twitter

Writing cron.php :

<?php
//include the abraham's twitteroauth library
require_once ('twitteroauth/twitteroauth.php');
//create an app and get the settings from dev.twitter.com
$consumerKey = ""; //add the key from your app
$consumerSecret = ""; //add the secret from your app
$accessToken = ""; //add the access token from your app
$accessSecret = ""; //add the access secret from your app
$message = "Why don't you try this one?";
$connection = new TwitterOAuth($consumerKey,$consumerSecret,$accessToken,$accessSecret);
$connection -> post('statuses/update', array('status' => $message ));
?>


The first line in the cron.php page, is to include the twitteroauth library by Abraham Williams.

Now we’re going to add the Consumer Key, Consumer Secret, Access Token, and the Access Secret that we have when we created the app with Twitter at http://dev.twitter.com

The lines that follow the keys and secret are the basic methods to tweet with Abraham’s twitteroauth.

Setting UP Cron on Server :

Now we’ve everything else ready with the code, we need to script  to run on its own.

Here it comes some linux command that needs to be done with your server.

If you’re using a similar CPanel Set Up as much like Godaddy, its easy to run the job.  I am not 100% sure about

Login to your cpanel and look for something named “Cron Jobs”.

Once you find it, go to Add New Cron Job and select the option to set time (in minutes, hours or days)

And the somthing similar to the following command.

php home/servername/public_html/foldername/cron.php

 

Conclusion :

As much as it sounds simple, you can try it too with your server provider.

You can also download the files from the GitHub Repository .

Make sure you add the keys, secrets, and tokens from your app (created at Twitter Dev).

Photo Credit : Flickr