Hi all,
I wanted to let the user define a time, on which a certain callback should be triggered and came up with the following concept. I am pretty sure there is room for improvement, so I am looking for feedback
from dash import Dash, Input, Output, State, html, dcc
import dash_mantine_components as dmc
import datetime
app = Dash(__name__)
app.layout = html.Div(
[
html.H4('Enter start time for the callback'),
dmc.TimeInput(
id='time_in',
style={"width": 150},
withSeconds=True,
),
html.Br(),
html.Button(
'submit',
id='btn'
),
dcc.Interval(
id='interval',
interval=1000,
n_intervals=0,
max_intervals=0
),
html.Br(),
html.Div(id='dump'),
]
)
@app.callback(
Output('interval', 'max_intervals'),
Output('interval', 'interval'),
Input('btn', 'n_clicks'),
State('time_in', 'value'),
prevent_initial_call=True
)
def update(_, value):
# convert into datetime object
start_time = datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%S')
# get current system time
now = datetime.datetime.now()
# how long until the callback should get triggered (in milliseconds)?
difference = (start_time - now).total_seconds() * 1000
return 1, difference
@app.callback(
Output('dump', 'children'),
Output('interval', 'n_intervals'),
Input('interval', 'n_intervals'),
State('interval', 'interval'),
prevent_initial_call=True
)
def out(_, wait):
return html.H4(
[
f'You had to wait {wait} milliseconds',
html.Br(),
f'The callback finished {datetime.datetime.now()}'
]
), 1
if __name__ == "__main__":
app.run(debug=True)