Background tasks are an issue for any web-based service. I don't think using a thread would be a good idea even if you could figure out howto get it to work. There's likely some timeout threshold you'd encounter. Either in nginx or whatever server you're using.
In my Ruby Sinatra/Rails days, I used to use [delayed_job](https://github.com/collectiveidea/delayed_job) which would use a database to serialize the job code. There was also a daemon running which would poll the database and run the jobs. [Sidekiq](https://github.com/sidekiq/sidekiq) was another popular option for Rails. It uses redis instead of a database. If you're hosting this in the cloud, another option is to move your job logic to a cloud function or cloud run job and trigger it from your web service via publishing a message/data to a pub/sub topic. Your cloud function can be triggered by the pub/sub, or your cloud run job can be scheduled and it can pull from the pub/sub. Those are the models I use now in most of my projects.