How can I perform calculations in the backgroundΒΆ
You can use this code in the task server module to run a background thread in the web application once a 3 minutes (can be changed by setting interval) to perform some calculations:
import threading
import time
import traceback
def background(task):
interval = 3 * 60
time.sleep(interval)
while True:
if not time:
return
with task.lock('background'):
try:
print('background')
# some code to execute in background for example:
# tracks = task.tracks.copy()
# tracks.open()
# for t in tracks:
# t.edit()
# t.sold.value = #some value
# t.post()
# tracks.apply()
except Exception as e:
traceback.print_exc()
time.sleep(interval)
def on_created(task):
bg = threading.Thread(target=background, args=(task,))
bg.daemon = True
bg.start()
Note
When multiple web applications are running in parallel processes, the background function will be executed in each process. To prevent simultaneous execution of this function, we use the lock method of the task.
Note
The Jam.py V7 introduced the calculated field. It is now possible to use the server side functions (SUM, COUNT, MIN, MAX, AVG), for the lookup to some other table field in a Master/Detail scenario. The Users might review the server side calculations code and replace it with a calculated fields, if appropriate.