Hello, what is the correct way to launch a backgro...
# ktor
l
Hello, what is the correct way to launch a background job that won't affect the handling of the current request? My use case: 1. User creates a resource with a POST request 2. launch a job to generate a pdf based on the created resource (I don't want this step to interfere with the request handling) 3. return the id of created resource
since ktor is all coroutine based i thought about using GlobalScope to launch this job, but coroutines docs doesn't really recommend the usage of GlobalScope unless is strictly necessary
image.png
image.png
m
I'd recommend to create supervisorScope somewhere before accessing routing and use it instead of the GlobalScope. https://kotlinlang.org/docs/exception-handling.html#exceptions-in-supervised-coroutines here it's an example of doing it with proper error handling
j
The real answer is using a queue and pushing the pdf generation job to it, to consume it right after. That way, if the generation crashes for whatever reason, you will not lose the task you assigned to the consumer.
👍 1
m
That's the ultimate solution, but not a real answer to the question. If it's just few PDFs per day, there's no point on introducing the whole architecture for that. Everything depends on requirements here.
1
j
You’re right, it is not a direct answer to the question 😅 However, no need for something fancy. The queue can be done in the same database used to store the data. It’s only to bring a bit of reliability from scratch :)
m
Assuming there's a DB in place 😁
☝️ 2
f
@Lucca Beurmann Maybe it's an overkill, but if you want something that would ensure the job is scheduled even if the server restarts, then you could use Quartz. I recently created a pet project example to send email or slack notifications with Quartz using Ktor. It is quite easy to refactor it to generate PDFs instead, or any type of custom action at desired times. https://github.com/perracodex/KTask
l
This is a project for personal use so scale is not really an issue. As I said before i'm not very literate over backend thing so i'm kinda lost here haha awkward monkey
Thanks for the suggestion @Fernando Sanchez (Perraco Labs) but this is indeed an overkill, i'm looking for something simpler