Bookmark
Creating an interval task
Introduction
Sometimes an agent will need to perform a task periodically. To do this we can use the on_interval()
decorator which periodically repeats a given function for the agent. For instance, an agent could send a message every 2 seconds to another agent.
Let's get started and create our first interval task!
Walk-through
-
Let's create a Python script for this task, and name it by running:
touch interval-task.py
-
Then import the necessary classes from
uagents
library,Agent
andContext
, and create our agent:from uagents import Agent, Context alice = Agent(name="alice", seed="alice recovery phrase")
-
We can now define our agent's behavior:
@alice.on_interval(period=2.0) async def say_hello(ctx: Context): ctx.logger.info(f'hello, my name is {ctx.name}') if __name__ == "__main__": alice.run()
The output will be printed out using the
ctx.logger.info()
method. -
Save the script.
The overall script should look as follows:
interval-task.py
from uagents import Agent, Context
alice = Agent(name="alice", seed="alice recovery phrase")
@alice.on_interval(period=2.0)
async def say_hello(ctx: Context):
ctx.logger.info(f'hello, my name is {ctx.name}')
if __name__ == "__main__":
alice.run()
Run the script
Run the script: python interval-task.py
The output should be as follows:
hello, my name is alice
hello, my name is alice
hello, my name is alice