[Python] how to call async function for timer in python

Discussão em 'Python' iniciado por Stack, Março 27, 2025.

  1. Stack

    Stack Membro Participativo

    I would like two parameters: freq1 and freq2 to swap at a interval freq_change_interval - this is in a existing python project which already uses async in some methods, but the existing main(): method is not async.

    The parameters are from the command line arguments, and the context of the project is that it reads in data from a software defined radio (SDR).

    A cutdown copy of the module containing main(): looks like this:

    import asyncio
    import argparse
    from tracker.common import ProcessConfig, ProcessResult, SampleConfig

    def main():
    p = argparse.ArgumentParser()
    ...
    s_group = p.add_argument_group("Sampling")
    ...
    s_group.add_argument(
    "--freq1",
    dest="freq1",
    type=float,
    default=SampleConfig.freq1,
    help=" frequency 1 (default: %(default)s)",
    )
    s_group.add_argument(
    "--freq2",
    dest="freq2",
    type=float,
    default=SampleConfig.freq2,
    help=" frequency 2 (default: %(default)s)",
    )
    s_group.add_argument(
    "--interval",
    dest="freq_change_interval",
    type=float,
    default=SampleConfig.freq_change_interval,
    help=" interval (default: %(default)s)",
    )

    ...

    sample_config = SampleConfig(
    freq1=args.freq1,
    freq2=args.freq2,
    freq_change_interval=args.freq_change_interval,
    )

    async def other_methods():

    async def results_pipeline(....)

    if __name__ == "__main__":
    main()


    I have read about async functions and the minimum examples I have seen I can not integrate into the context of the existing code.

    Q: How can I have something working that resembles the pseudo code:

    if sample_config.freq_change_interval > 0:
    await asyncio.sleep(sample_config.freq_change_interval)
    freq1, freq2 = freq2, freq1 # swap frequencies when interval is reached

    Continue reading...

Compartilhe esta Página