Search code examples
timerjulia

How do I repeat my custom function every 15 minutes? (Julia)


I was trying to write a function that would take the amount of players currently logged into oldschool runescape and append the amount with the current time and date into a csv file. This function works great, but when I try to use the Timer function to repeat the function multiple times it shows an error. (I want it to run every 15 minutes on my idle laptop indefinitely).

This is the function:

function countplayers()
    res = HTTP.get("https://oldschool.runescape.com")
    body = String(res.body);
    locatecount = findfirst("There are currently", body);
    firstplayercount = body[locatecount[end]+2:locatecount[end]+8]
    first = firstplayercount[1:findfirst(',',firstplayercount)-1]
    if findfirst(',',firstplayercount) == 3
        second = firstplayercount[findfirst(',',firstplayercount)+1:end-1]
    else
        second = firstplayercount[findfirst(',',firstplayercount)+1:end]
    end
    finalcount = string(first,second)
    currentdate = Dates.now()
    concatenated = [finalcount, currentdate]
    f = open("test.csv","a")
    write(f, finalcount,',')
    write(f, string(currentdate), '\n')
    close(f)
end

If I try Timer(countplayers(),10,10) to test it out, I get this error:

**ERROR: MethodError: no method matching Timer(::Nothing, ::Int64, ::Int64)**

The same error appears if the timer is placed below the function and if the timer command is used in the REPL. What am I doing wrong? Thanks in advance!


Solution

  • The canonical way to do this is to start an async task and just run it in a loop and sleep in between:

    @async while true
        my_function()
        sleep(15*60)
    end
    

    Because this block is async, evaluating this will return immediately and the task will just run in the background until the program exits.