Fabian Breuer
Fabian Breuer

Reputation: 39

While Loop with time.sleep

i will use a while loop for a refresh for a method.

def usagePerUserApi():
    while True:
        url = ....
        resp = requests.get(url, headers=headers, verify=False)
        data = json.loads(resp.content)
        code = resp.status_code
        Verbindungscheck.ausgabeVerbindungsCode(code)

        head =.....

        table = []
        for item in (data['data']):
            if item['un'] == tecNo:
                table.append([
                    item['fud'],
                    item['un'],
                    str(item['lsn']),
                    str(item['fns']),
                    str(item['musage'])+"%",
                    str(item['hu']),
                    str(item['mu']),
                    str(item['hb']),
                    str(item['mb'])
                ])
        print(tabulate(table,headers=head, tablefmt="github"))
        time.sleep(300)

If I leave time.sleep like this, it will be displayed as an error. If I put it under the while loop, It will be updated constantly and does not wait 5 minutes.

I don't know where the mistake is. I hope you can help me.

Upvotes: 0

Views: 302

Answers (2)

Adi219
Adi219

Reputation: 4814

Have you imported the time library? If not, then add

import time

to the top of your code, and it should work.

Also bear in mind that there may be problems with output buffering, where the program won't wait as expected, and so you'll need to turn it off, as shown by this answer.

Upvotes: 1

rsedlr
rsedlr

Reputation: 100

You need to import the python time library

If you place

import time

at the top of your file it should work

Upvotes: 3

Related Questions