cron is added but not executing current time

94 views Asked by At

following is my recipe I am trying to create a new text file with current time and date

cron 'cron_disply_time' do
  minute '*/1'
  command "echo #{Time.new.strftime("%Y-%m-%d %H:%M")} > /home/vagrant/learn-cron/cookbooks/t.txt"
  action :create
end

Its always taking the time when the job was added

*/1 * * * * echo 2020-05-07 14:06 > /home/vagrant/learn-cron/cookbooks/t.txt

can some please let me know how can I make it executable with the recipe only

2

There are 2 answers

1
AudioBubble On BEST ANSWER
cron 'cron_disply_current_time' do
  minute '*/1'
  command 'NOW=$(date +"%T") && sudo echo "Current time:"  $NOW > /home/vagrant/current_time.txt'
  action :create
end

date will show the current date

NOW=$(date +"%T") will show the time

sudo echo "Current time:" $NOW > /home/vagrant/current_time.txt' will add "Current time:" 11:14:19 into current_time.txt file

0
Draco Ater On

cron resource generates a static file with the command inside it, so yes, it will put 1 and the same string into the file.

In bash current time one can get by calling date

$ date
Fri May  8 09:58:39 EEST 2020

So you can use this function inside your cron to get the current time like this:

cron 'cron_disply_time' do
  minute '*'
  command 'date "+%F %H:%M" > /home/vagrant/learn-cron/cookbooks/t.txt'
  action :create
end