How to deal with threading

I try to use ‘threading.Thread()’ to hold selected orders 30 seconds, when time up, thread dead and trigger a function to delete these selected order automatically. I also use thread.join() ,which I use it to try not let any single thread stop host progress . but I failed , and thread still stop hos progress when they were called.

This is my first time use threading, I stuck this problem for two days. But this feature is important in my plan, I don’t want to cut it off. Could any one share some experience with me? thanks!

Using threads on the server is not safe. The server doesn’t know that you are using threads, could kill them (as you found out) and doesn’t work with data tables (see here).

You can use threads on your uplink modules, but you might still have problems working with the data tables.

You should look at Background Tasks. They are the official way to start a background thread that is data table friendly, doesn’t stop when your request stops, doesn’t timeout and can be monitored or killed by another function.

2 Likes

Thank you so much for explicit explaining! I will try that.

It looks like working well without halting control flow, I mean, it did hold 30 sec without blocking host progress, and deleted target row, but why did it fail to print out, and without display anything in label?

I have not tried to print from a background task.

I would expect for it not to print to the console, but its output should be visible on the app log (click on the gear on the IDE). Let me know, if it doesn’t work I will try.

1 Like

you are right, it it visible on the app log. like a magic…

the question is ,why was that? background task only wok on data tables? how could it work on front_end Form?

Background tasks cannot interact with the form because they run on the server, not on the client.

The code on the client calls a function on the server, that function starts the background task and returns something to the client, the code on the client changes something on the form and ends. There is no way for the background task to contact the client and send some information.

You could use a timer on the form to call another server function that checks the status of the background task or checks the database modified by the background task.

Or, if the job done by the background task is fast, you could use a timer with 30 seconds instead of a background task. But you can do this only if it’s ok for the delayed job not to run if the user closes the browser before the timer ticks.

1 Like

Nice explanation! you really know what I was looking for. Thanks!

What kind of library do you mean for implementing this timer?

No need to bother any libraries, Anvil has the timer component for you:
image

2 Likes