Recreate job after another job is completed

落爺英雄遲暮 提交于 2019-12-23 16:14:10

问题


I have the following situation: job1 and job2 go to the server in the same time and both of them came back with status 401, which means that my token access has expired and I need to make a refresh. I start job3 which came back the new token. In this case, I have to recreate the job1 and job2 with the new token on request and start them. I have a jobDispatcher, but it seems that it not help me in situation. Here it is :

class JobDispatcher : CoroutineDispatcher() {
  private val queue: Queue<Runnable> = LinkedList()
  private var isPaused: Boolean = false
  private var lastExecutedBlock: Runnable? = null

  @Synchronized
  override fun dispatch(context: CoroutineContext, block: Runnable) {
    if (isPaused) {
      queue.add(block)
    } else {
      thread {
        lastExecutedBlock = block
        block.run()
      }
    }
  }

  @Synchronized
  fun pause() {
    isPaused = true
    if (lastExecutedBlock != null) {
      queue.add(lastExecutedBlock)
      lastExecutedBlock = null
    }
  }

  @Synchronized
  fun resume() {
    isPaused = false
    runQueue()
  }
}

Pause method is called before job3 to start, and when the result is successful, resume method is called. The problem is that job1 and job2 are now completed and now I should recreate them. Is there any possibility to clone the job, and put it in a queue?

My question is: which is the best solution to solve this? I fell a little lost when working with coroutines. My code is much complicated then I described here, I need just some guidelines for this situation, how to manage it. How to communicate between coroutines?

Any idea is welcome. Thank you!


回答1:


I would make job1 and job2 fetch the access token at the beginning of themselves (fetch the access token from redis or something else). And then if access token expires, start job3 to update the access token, and then resume all the jobs. I don't know how your job worker and job dispatcher are like, but many implementations in the open source world have the ability to delay and retry a failed job. If yours doesn't have this ability, you have to recreate jobs, but no need to worry about the access token, since it will be fetched at the beginning of the job.

IN SHORT: Don't hardcode the access token in source code. Don't encode the access token in the job data. Just fetch the needed access token when it is needed.



来源:https://stackoverflow.com/questions/55647810/recreate-job-after-another-job-is-completed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!