Python [How to] : Playing with Croniter

Playing with Croniter

How many seconds / minutes to the next cronjob? perhaps it is the question when we use a cronjob for some our applications.

Here I will show you a little trick using croniter, in the future, it will be combined with Redis Caching and News Web Crawler.

Installation

It is easy, pip install croniter or go to pypi croniter page.

The code

#!/usr/bin/python

# Author  : Fajri Abdillah a.k.a clasense4
# Twitter : @clasense4
# mail    : clasense4@gmail.com

import croniter
import datetime
import time

now = datetime.datetime.now()
now2 = time.mktime(now.timetuple())
sched = '*/20 * * * *' # every 20 minutes
cron = croniter.croniter(sched,now)

print "Next Cron job : %s (Seconds) | Now : %s " % ( cron.get_next() - time.mktime(now.timetuple()), datetime.datetime.now()) #to next 20 minutes
#print "Next Cron job : %s (Minutes) | Now : %s " % ( datetime.timedelta(seconds=cron.get_next() - time.mktime(now.timetuple())), datetime.datetime.now())

Explanation

Why I comment on next print , because if I not comment that, the code will be fail, cron.get_next() will call the next cron function, it means next 40 minutes. Just try to comment / uncomment print section, and you’ll know 😀

Conclusion

This simple post is just to show how to use python with cron using croniter. And in my opinion, it’s so helpfull 😀

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s