File size: 1,327 Bytes
2b4d75c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Background Tasks / Executor
# Use q.exec() to execute background functions using a thread-pool or process-pool.
# #background_tasks #executor
# ---
import time
import random
import concurrent.futures
from h2o_wave import main, app, Q, ui


def blocking_function(secs) -> str:
    time.sleep(secs)  # Blocks!
    return f'Done waiting for {secs} seconds!'


@app('/demo')
async def serve(q: Q):
    if q.args.start:
        q.page['form'] = ui.form_card(box='1 1 6 2', items=[ui.progress('Running...')])
        await q.page.save()

        seconds = random.randint(1, 6)

        # DON'T DO THIS!
        # This will make your app unresponsive for some time:
        # message = blocking_function(seconds)

        # Do this instead:
        with concurrent.futures.ThreadPoolExecutor() as pool:
            message = await q.exec(pool, blocking_function, seconds)

        # You can also pass a ProcessPoolExecutor, like this:
        # with concurrent.futures.ProcessPoolExecutor() as pool:
        #    message = await q.exec(pool, blocking_function, seconds)

        q.page['form'] = ui.form_card(box='1 1 6 1', items=[ui.message_bar('info', message)])
        await q.page.save()
    else:
        q.page['form'] = ui.form_card(box='1 1 2 1', items=[ui.button(name='start', label='Start')])
        await q.page.save()