How to know when a task is done?

If I create a Task using @async, and want to do something (like changing some status) immediately after that task is done, how do I do that? I guess istaskdone can only let me check everytime manually. I don’t quite understand notify & Condition, do they just notify me, or I can run some functions?

You can wait the task to finish.

How? I don’t want wait to block my following commands. What I want is scheduling a Task and then do my things. When the Task is done, it will notify me, or do more things, like writing some text to a file, etc.

Then you can simply create another Task, inside of which you wait for the previous task.

2 Likes

Also you can just add this command inside your task

@async begin
   # commands of your original task
    # do something, when previous commands are complete
end

What do you mean by “notify me”?

1 Like

What do you mean by “notify me”?

Sorry if I was unclear. I want a Task that can handle some jobs for me while not blocking what I am doing ( @async ). But when that Task is done, I can immediately know it instead of checking with istaskdone each time manually. Also, I may want it to change the status of the job from Running to Succeeded or Failed , etc. And I may also want to do some other things immediately when the Task is done.
You can see my code here. I used @spawn to do this, but it is not the most simple way, I think.

Is this for use in an interactive Julia environment, or for a program to run by itself?

Both. I want it to be programmable as scripts and also interactive.

The problem is that, even with your clarification, “notify me” is ill defined. You are not your program after all - there is no automatic message queue or notification bar or something like that, you’ll have to create something that handles finished tasks for you. This is what @findmyway meant when they mentioned you have to create another Task that handles those for you. One way to achieve that is to have each task you spawned take e.g. a Channel to put results, errors etc. into and have a number of other tasks pull results out of that channel and act according to whatever that result is (e.g. spawn new tasks, write them to a file, etc.)

If you want it to work interactively, I’d look into ReplMaker.jl. You will have to decouple the interactive part from the standalone part, else your code will probably beome a lot harder to maintain.

Something like

@sync begin
    c = Condition()
    @async begin
        for i in 1:5
            println("I am doing work in the background...")
            sleep(0.5)
        end
        notify(c)
    end

    @async begin
        wait(c)
        println("I got notified")
    end
end

with output:

I am doing work in the background...
I am doing work in the background...
I am doing work in the background...
I am doing work in the background...
I am doing work in the background...
I got notified

?

5 Likes