Rich Starkie
Rich Starkie

Reputation: 45

Calculating elapsed time and saving to database

I'm trying to log in a Ruby app DB Table (MySQL Database), the time and date that an import script started, finished and how long the script took to execute.

The logging of the start time and finish time is easy enough, and I've got that working, however, I can't get it to save the runtime in the table, it just skips the field.

Here's the table structure from the Migration file

create_table :import_alls do |t|
  t.datetime :Import_Start_Time
  t.datetime :Import_Finish_Time
  t.time :Import_Duration


  t.timestamps
end

Here's my code ...

@script_start_time = Time.now
[... Script ...]
@script_finish_time = Time.now
@script_runtime = @script_finish_time - @script_start_time

import = ImportAll.new
    import.Import_Start_Time = @script_start_time # Saves correctly
    import.Import_Finish_Time = @script_finish_time # Saves Correctly
    import.Import_Duration = @script_runtime # Skips
    [... a few other fields to save ...] # All save correctly
import.save!

puts @script_runtime # Puts correct number of seconds as a line in the server log

Saved Results :

Import_Start_Time = Start Date & Time as expected
Import_Finish_Time = Finish Date & Time as expected
Import_Duration = NULL (expected duration expressed as HH:MM:SS)

So,

  1. is a time field the correct type if field? or should it be datetime ?

  2. how can I convert the @script_runtime value into a time field so it can be saved in the table ?

Upvotes: 0

Views: 262

Answers (1)

claasz
claasz

Reputation: 2144

Could be some data type conversion issue:

2.6.3 :018 > t = Time.new(12.023267542)
=> 0012-01-01 00:00:00 +0053 

Instead of time, I'd use an integer column to store the duration.

Upvotes: 1

Related Questions