Why does my code error out only when running in autostart?

Hello,

I am trying to create a Halloween special effect: Shepherd’s Tone Falling, that will start automatically on bootup on my raspberry pi 4 without needing to plug in a monitor or keyboard. When I start this code with Sonic Pi already running, it works just fine. But when I let it start up on its own (by including the code in init.rb, and with the auto startup set up, it always errors out on Thread Death the thread is too far behind time.

starting_note = note(:C6)
ending_note = note(:C2)
puts starting_note
puts ending_note
total_octaves = 3
octave_duration = 15
total_waves = 20
wave_duration = octave_duration * total_octaves
fade_in_out_duration = wave_duration * 0.2

target_notes = octs(ending_note, total_octaves + 1)
puts target_notes
new_notes = target_notes.reverse()
puts new_notes

in_thread do
  this_octave = total_octaves
  loop do
    sync :new_octave
    in_thread do
      with_synth :sine do
        instrument = play starting_note,
          note_slide: octave_duration,
          attack: fade_in_out_duration, release: fade_in_out_duration,
          decay: 0, sustain: (wave_duration - 3 * fade_in_out_duration)
        
        total_octaves.times { |octave|
          cue :new_octave
          control instrument, note: new_notes[octave]
          puts new_notes[octave]
          this_octave -= 1
          sleep octave_duration
        }
      end
    end
    sleep (octave_duration/2)
  end
end

in_thread do
  cue :new_octave
end

I thought I had somehow gotten this to reliably work on autostart, but then I changed my audio output from the headphone jack on the raspberry pi for a USB dongle that I can plug a 3.5mm speaker jack into (because of all of the static that the raspberry pi outputs), and now I can’t get it to run on autostart.

Could I please get help correcting this code so that it will run just fine even with autostart?

I would try adding a fairly long sleep at the beginning to give Sonic Pi more time to finish starting up before the main code starts.

You could also try using set_sched_ahead_time! to increase the default schedule-ahead time.

I’m not sure if either of those will fix it, but I think they’re worth a try.

I’ve found there are issues with this on recent SP versions and I haven’t been able to fully resolve them. Init.rb is really intended to hold functions that you want to use regularly just defining them rather than running music programs. It seems worse running headless too. I’ve not tried it on the new Pi OS yet. We’ve been doing work on tha today and hope release a built installer soon.
Symptoms at present are that the timing seems to go astray. What corrects it is running something from a sonic pi buffer. Until you have done that it is not very happy. Same effect running via sonic-pi-cli last time I tried on startup.