-1

I am currently working on asyncio with python 3.7.x not sure about the exact version, right now I am trying to schedule a task. And I am unable to get an output, even when running the thing forever. Here is the code I currently have

import asyncio

async def print_now():
  print("Hi there")

loop = asyncio.get_event_loop()
loop.call_later(print_now())
loop.run_until_complete(asyncio.sleep(1))

This gives the following error:

Traceback (most recent call last):
  File "D:\Coding\python\async\main.py", line 7, in <module>
    loop.call_later(print_now())
TypeError: call_later() missing 1 required positional argument: 'callback'

The call back in call_later() is print_now I've tried just print_now and print_now() I have also tried using loop.run_forever() instead of loop.run_until_complete() and so far I didn't get anything

Sometimes I get either no output or a different error.

YJH16120
  • 419
  • 1
  • 4
  • 15
  • Did you read the error message and [how `call_later` works](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_later)…? – deceze Nov 11 '20 at 14:06
  • Look at the documentation for [call_later](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_later). You're missing a parameter. – larsks Nov 11 '20 at 14:06

1 Answers1

2

First, yes, you're missing a delay argument . First one is supposed to be the delay while the second one is a callback (docs).

loop.call_later(delay, callback, *args, context=None)

Second, the callback is supposed to be a function. What you're passing is print_now() which is gonna evaluate to None. You might find out that

'NoneType' object is not callable

So you're gonna need to pass print_now — without parentheses — as a callback. This way you're passing a function instead of the result of its application.


Third, async functions are supposed to be awaited on. Your scenario doesn't seem to need that, so just drop the async keyword.

When you call an awaitable function, you create a new coroutine object. The code inside the function won't run until you then await on the function or run it as a task

From this post. You might want to check out

Paul
  • 1,085
  • 12
  • 20
  • Oh can't believe I missed that part. Guess I wasn't paying attention. Thanks. – YJH16120 Nov 11 '20 at 14:23
  • 1
    Note that, with `print_now` defined as in the question, `print_now()` won't evaluate to None, but to a fresh coroutine object. It doesn't change anything, it still won't be callable, it's just the error that will be different. – user4815162342 Nov 11 '20 at 18:57