如何每15分钟重复一次自定义功能? (朱莉娅)

时间:2020-11-10 15:38:17

标签: timer julia

我正在尝试编写一个函数,该函数将当前登录到Olde Runescape的玩家数量并将该数量以及当前时间和日期附加到一个csv文件中。该函数很好用,但是当我尝试使用Timer函数多次重复该函数时,它显示错误。 (我希望它无限期地在闲置的笔记本电脑上每15分钟运行一次。)

这是功能:

button =  driver.find_element_by_css_selector('#root > section > section > div.ant-row > div:nth-child(2) > div.ant-spin-nested-loading > div > div > div > div > div.ant-collapse-content.ant-collapse-content-active > div > div > div > div:nth-child(17) > button.ant-btn.ant-btn-primary')
button.click()

如果我尝试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 进行测试,则会收到此错误:

Timer(countplayers(),10,10)

如果将计时器放在函数下方,并且在REPL中使用了timer命令,则会出现相同的错误。 我究竟做错了什么?预先感谢!

3 个答案:

答案 0 :(得分:2)

在Stefan的建议的基础上,扩展了完整的工作且非常有用的代码:

function dosomething(f, interval) 
    stopper = Ref(false)
    task = @async while !stopper[]
        f()
        sleep(interval)
    end
    return task, stopper
end

现在让我们看看这个动作:

julia> task, stopper = dosomething(()->println("Hello World"),10)
Hello World
(Task (runnable) @0x000000001675c5d0, Base.RefValue{Bool}(false))

julia> Hello World
julia>

julia> stopper[]=true;  # I do not want my background process anymore running


julia> task    #after few seconds the status will be done
Task (done) @0x000000001675c5d0

最后,还应注意,在生产系统中,最可靠的方法通常是使用诸如crontab之类的系统工具来控制和管理此类重复发生的事件。

答案 1 :(得分:2)

除了其他答案,这是另一种解决方案,与您尝试执行的操作更加内联:

julia> using Dates
julia> function countplayers()
           println("$(now()) There are 42 players")
       end
countplayers (generic function with 1 method)

# Run `countplayers` every 3s, starting now (delay=0)
julia> t = Timer(_->countplayers(), 0, interval=3);
2020-11-10T17:52:42.904 There are 42 players
2020-11-10T17:52:45.896 There are 42 players
2020-11-10T17:52:48.899 There are 42 players
2020-11-10T17:52:51.902 There are 42 players
2020-11-10T17:52:54.905 There are 42 players
2020-11-10T17:52:57.908 There are 42 players
2020-11-10T17:53:00.909 There are 42 players

# When you want to stop the task
julia> close(t)

答案 2 :(得分:1)

做到这一点的典型方法是启动一个异步任务,然后将其循环运行并在之间休眠:

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

由于该块是异步的,因此评估将立即返回,并且该任务将仅在后台运行,直到程序退出。