snippetrubyMinor
Small script to re-create a file indefinitely
Viewed 0 times
scriptfilecreateindefinitelysmall
Problem
I created a small ruby script at work to recreate a text file I use for a test in the Java application we are supporting.
I'm still really new to the ruby paradigm and wanted to know if that small script respect most of the spirit of it.
The content of the file doesn't need to make sense since the only requirement I have is that a file exist.
Since I'm doing my test every minute mostly, I set the sleeping time between checking the existence of the file to 30 seconds.
Could I do better? I'm on Windows and using JRuby, is there something I'm missing with my code being portable ?
Obvisously, I could make the path an argument of my script, but I don't need this at the moment.
I'm still really new to the ruby paradigm and wanted to know if that small script respect most of the spirit of it.
The content of the file doesn't need to make sense since the only requirement I have is that a file exist.
Since I'm doing my test every minute mostly, I set the sleeping time between checking the existence of the file to 30 seconds.
require 'pathname'
PATH = "C:/folder/to/file/test1.txt"
SLEEP_TIME = 30
path_to_text_file = Pathname.new(PATH)
while (true)
unless path_to_text_file.exist? then
File.open(PATH, "w") {|f| f.write("test") }
puts "File #{PATH} created"
end
puts "Sleeping for #{SLEEP_TIME} seconds"
sleep(SLEEP_TIME)
endCould I do better? I'm on Windows and using JRuby, is there something I'm missing with my code being portable ?
Obvisously, I could make the path an argument of my script, but I don't need this at the moment.
Solution
Unless you really want to reinvent the wheel, you could use
Updates modification time (mtime) and access time (atime) of file(s) in list. Files are created if they don’t exist.
For example:
FileUtils.touch for this:FileUtils.touchUpdates modification time (mtime) and access time (atime) of file(s) in list. Files are created if they don’t exist.
For example:
require 'fileutils'
PATH = "C:/folder/to/file/test1.txt"
SLEEP_TIME = 30
loop do
FileUtils.touch(PATH)
sleep(SLEEP_TIME)
endCode Snippets
require 'fileutils'
PATH = "C:/folder/to/file/test1.txt"
SLEEP_TIME = 30
loop do
FileUtils.touch(PATH)
sleep(SLEEP_TIME)
endContext
StackExchange Code Review Q#136669, answer score: 5
Revisions (0)
No revisions yet.