Real Time Logging

Hey guys

I am trying to log some data down - it is going well, but I want to do real time logging. Currently my code like this:

date = `cmd /c date /t`
time = `cmd /c time /t`


datestr = chomp(read(date,String))
timestr = chomp(read(time,String))


headerini  = "DATE" * "             " * "TIME" * "\r\n"

try
rm("myfile.txt")
catch
end

io = open("myfile.txt", "w");
write(io, headerini);
close(io)

for i = 1:5
    io = open("myfile.txt","a");
    datestr = chomp(read(date,String))
    timestr = chomp(read(time,String))
    table =  datestr * "      " * timestr * "\r\n"
    println(table)
    write(io, table);
    sleep(5)
    close(io)
end

I want to do it real time, which is working currently, but I constantly have to open and close the same file - when I tried to use append functionality it was not real time, but only when my script ended. Is the way I am doing it now correct or can I improve it?

Kind regards

1 Like

IO is normally buffered before writing to disk because writing to disk is slow.
because the disk has to move its writing cursor into place.

The buffer is flushed (written out to disl) under the following conditions:

  • when flush!(io) is called
  • when close(io) is called.
  • when a open IO stream is garbage collected
  • when your program exits
  • approximately every 4000bytes written to the IO stream.

So the short answer is call flush! after write!.

5 Likes

Ah thanks, so now I did it as you say, I think atleast:

io = open("myfile.txt", "w");
write(io, headerini);
close(io)

io = open("myfile.txt", "a");

for i = 1:5
    datestr = chomp(read(date,String))
    timestr = chomp(read(time,String))
    table =  datestr * "      " * timestr * "\r\n"
    println(table)
    write(io, table);
    flush(io)
    sleep(5)
end

close(io)

So now I only open twice, first to insert the header and then append the rest of the data. Is this as you thought?

Kind regards

sure, if you want.
You might like to learn to use the do block form
which closes at the end of the do block.

open("myfile.txt", "w") do io
    write(io, headerini);
end
1 Like

Please, please forgive me if I am putting my foot in my mouth.
It looks like you are calling the Windows utilities for date and time.
To make a programme more portable you could use Julia functions
https://en.wikibooks.org/wiki/Introducing_Julia/Working_with_dates_and_times

I really, really do not want to appear to be a smartarse here.
Also you may be getting the time from the system deliberately.

1 Like

Thanks @oxinabox will try to change it to that syntax.

You are right @johnh probably smarter to use Julia directly - the only reason for using CMD was in the beginning I tried to code as an batch file, but I got stuck so went and made it inside Julia instead - thanks for the link!