Search code examples
pythontimeslack

how ro run python func 10 a.m. every day


Func should run at 10 a.m with one arg, 11 another, but I am not sure what to use. Are there library for that sake? That is my function:

import os
from slackclient import SlackClient

BOT_NAME = "bot"
SLACK_API_TOKEN = "token"
BOT_ID = "id"

sc = SlackClient(SLACK_API_TOKEN)


def send_message(text):
    sc.api_call(
        "chat.postMessage",
        channel="#madchickens",
        text=text
    )
send_message("here func work")

Solution

  • User @icedwater is right: scheduling something to run at a specific interval, time of day, day of week, day of month, etc. is a job best handled with a tried-and-tested *nix tool like crontab.

    Given that answer, however, you could modify your script to use the sleep(n) function in the time module, to allow your bot/script to do something every n seconds. Here's an example that would run an action every 24 hours:

    import time
    
    SECONDS_PER_HOUR = 3600
    HOURS_PER_DAY = 24
    
    while True:
        print("glorp")
        time.sleep(SECONDS_PER_HOUR*HOURS_PER_DAY)
    

    You could also use sleep to run a function every hour, and check what the hour number is, performing conditional actions based on the hour number (the hour number here is 24-hour format, so 0 for midnight, 12 for noon, 23 for 11 PM, etc.):

    import time
    import datetime
    
    while True:
        now = datetime.datetime.now()
        if(now.hour==8):
            print("bleep")
        if(now.hour==10):
            print("bloop")
        if(now.hour==23):
            print("blarp")
        time.sleep(3600)
    

    These are simple examples that could be easily replicated with a cron job, but you can see how this could be built out to implement much more complicated and interesting timing logic...