i am trying to wrap my head around scopes, still. ...
# coroutines
p
i am trying to wrap my head around scopes, still. most examples online are simplistic uses of
runBlocking
... use case here is that i need to, once a day run a bunch of operations as coroutines. currently this is a java scheduled executor, but i want to switch to coroutines for the actual running of the code.
i am thinking of using
runBlocking
and a bunch of
launch
calls inside of this
d
runBlocking
scope has only 1 thread. Use a scope like this,
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
Then
scope.launch { /*worker code */}
p
that looks about what i'm after, yes. the scope object is then used to join/wait/kill all the threads?
when scope dies, so does everything underneath
are there any built-ins of the corutine API for running a coroutine at a specific time? i know there is
timer
, but otherwise i guess i can use a scheduling library to actually fire up the workers
d
You can use the
delay
function after starting the coroutine
p
yes, couldu use that. although it's more like i have to schedule according to cron-esque policies
actually i can use delay + next execution time from spring scheduling, i think
d
If you want things to happen at a particular time, you might be better off using cron jobs to start a process
p
that is the most reliable approach, yes. right now i am just experimenting. but i want to in the end leverage a higher level cron facility
g
Use scope like this
I don't see why scope is needed in this case, just GlobalScope is fine for non cancellable scope of some background tasks
d
I wouldn't recommend using GlobalScope to someone who doesn't understand scopes
g
I wouldn’t recommend to use
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
to someone who doesn’t understand scopes
it doesn’t add any value or safety, just more code
sure, you can cancel scope, but in this sample you also easily can cancel
Job
d
It's just a decent example of what a scope can do and as should be evident, he immediately had a better idea of what scopes do
g
Fair enough
p
the proper solution is probably a supervisor scope, but right now i am just experimenting with converting a standard java scheduled executor service into something using coroutines
unfortunately all of this is backed by JPA at the moment, and the R2DBC library is not yet stable. so, i am not sure building coroutines on top will help that much
d
You can use executor.asCoroutineDispatcher() instead of Dispatchers.Default
p
that would be a good place to begin bridging