FUN WITH LINUX

Installing cronjobs out of scripts

26 June 2016

Sometimes it’s necessary to install cronjobs out of scripts. It’s not a good idea to directly write to /var/spool/cron/crontabs. Various things might happen like permission problems or simply problems with the format. It’s better to make this in two steps.

First create a crontab-file, like /tmp/mytmpcronfile0001:

*/5 * * * * echo hello world >> /tmp/hello.txt
30 22 * * * echo foo bar >> /tmp/hello.txt

Now we can install this crontab for the current user by calling crontab:

crontab /tmp/mytmpcronfile0001

To list all cronjobs we can use:

crontab -l

User root is also able to install cronjobs for other users:

crontab -u someuser /tmp/mytmpcronfile0001

Let’s do this in Ruby

The following code demonstrates how we can do this in Ruby. There is no error handling in this code, so be aware of this if you want to use it.

    #!/usr/bin/env ruby
    
    class Crontab
    	attr_accessor :hour
    	attr_accessor :min
    	attr_accessor :mday
    	attr_accessor :month
    	attr_accessor :wday
    	attr_accessor :command
    	
    	def initialize
    		@hour = '*'
    		@min = '*'
    		@mday = '*'
    		@month = '*'
    		@wday = '*'
    		@command = "/bin/false"
    	end
    end
    
    
    class Crony
    	attr_accessor :cronfile
    
    	def initialize(file)
    		@cronfile = file
    	end
    
    	def readfile
    		ret = Array.new
    
    		if not File.exist?(@cronfile)
    			raise "File doesn't exist"
    		end
    
    		file = File.open(@cronfile,"r")
    		file.each do |line|
    			if line !~ /^\s*#/
    				h = parse(line)
    				ret.push(h)
    			end
    		end
    		file.close
    
    		return ret
    	end
    
    	def writefile(hashy)
    		file = File.open(@cronfile,"w")
    		hashy.each do |cron|
    			file.write("#{cron.min} #{cron.hour} #{cron.mday} #{cron.month} #{cron.wday} #{cron.command}\n")
    		end
    		file.close
    		command = "crontab #{@cronfile}"
    		`#{command}`
    
    	end
    
    	def parse(line)
    		c = Crontab.new
    
    		if line =~ /(\*|\d+)\s(\*|\d+)\s(\*|\d+)\s(\*|\d+)\s(\*|\d+)\s(.+)$/
    			c.min = $1
    			c.hour = $2
    			c.mday = $3
    			c.month = $4
    			c.wday = $5
    			c.command = $6
    		else
    			raise "Invalid cron-entry"
    		end
    
    		return c
    	end
    
    end
    
    crony = Crony.new("/tmp/some_cronjob")
    
    
    arr = Array.new
    day = Crontab.new
    day.hour= "09"
    day.min="30"
    day.command='echo hello day >> /tmp/hello.txt'
    
    arr.push(day)
    
    night = Crontab.new
    night.hour= "22"
    night.min="45"
    night.command='echo hello night > hello.txt'
    
    arr.push(night)
    crony.writefile(arr)
[ Linux  Sysadmin  Ruby  Shell  ]
Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 Unported License.

Copyright 2015-present Hoti