例えば「9時までsleepして音楽を流す」ような処理をしたいとき、「今8時30分だからsleep 1800 && mplayer hoge.mp3」とかやっていたのですが、手作業で計算しても無駄なので、時間を指定してsleepするスクリプトを作ってみました。
実行例
$ sleeptill --verbose 2008-07-16 21:34 && echo "wake up" 8 seconds to Wed Jul 16 21:34:00 +0800 2008 7 seconds to Wed Jul 16 21:34:00 +0800 2008 6 seconds to Wed Jul 16 21:34:00 +0800 2008 5 seconds to Wed Jul 16 21:34:00 +0800 2008 4 seconds to Wed Jul 16 21:34:00 +0800 2008 3 seconds to Wed Jul 16 21:34:00 +0800 2008 2 seconds to Wed Jul 16 21:34:00 +0800 2008 1 seconds to Wed Jul 16 21:34:00 +0800 2008 0 seconds to Wed Jul 16 21:34:00 +0800 2008 wake up $ sleeptill 200807162215 && echo "wake up" wake up
特徴
- sleepみたいな感じで気軽に使える
- 日時の記法をいくつか用意した
- -vか--verboseで残り時間を表時
- -hか--helpで使用法を表示
ソース
#! /usr/bin/env ruby # suspend till specified time require 'time' # define def print_help puts "wait_till" puts "sleep_till -- suspend execution till specified time" puts "usage: wait_till 20080721112822" puts "usage: wait_till 200807211128" puts "usage: wait_till 20080721 1128" puts "usage: wait_till 2008.07.21/11:28:22" puts "usage: wait_till 2008.07.21/11:28" puts "-v or --verbose: show detail" puts "-h or --help: print this" exit end # options while ARGV[0][0..0] == '-' case ARGV.shift when '-v' verbose = true when '--verbose' verbose = true when '-h' print_help when '--help' print_help else print_help end end # parse specified time if ARGV[0].size == 14 # like 20080721112822 timer = Time.local(ARGV[0][0..3], ARGV[0][4..5], ARGV[0][6..7], ARGV[0][8..9], ARGV[0][10..11], ARGV[0][12..13] ) elsif ARGV[0].size == 12 # like 200807211128 timer = Time.local(ARGV[0][0..3], ARGV[0][4..5], ARGV[0][6..7], ARGV[0][8..9], ARGV[0][10..11] ) elsif ARGV[0].size == 8 # like 20080721 1128 timer = Time.local(ARGV[0][0..3], ARGV[0][4..5], ARGV[0][6..7], ARGV[1][0..1], ARGV[0][2..3], ARGV[1].size > 4 ? ARGV[1][4..5] : 0 ) else # like 2008.07.21/11:28:22 or 2008.07.21/11:28 timer = Time.local(*ARGV.join('/').to_s.split(/\D/)) end # wait for the time loop do exit if timer < Time.now if verbose puts "#{ (timer - Time.now).to_i } seconds to #{timer}" end sleep 1 end