On Thu, Feb 23, 2017 at 12:37 PM, Nathan Kerr <nat...@pocketgophers.com>
wrote:

> NewTicker function example
>
> The task of running functions on a periodic basis can be split into two
> parts: timing and execution.
>
> A ticker solves the timing problem by providing a channel that get new
> input every period. Keeping the timing separate mitigates the impact of
> execution on the timing period (e.g., it won’t be execution time + sleep
> time)
>
> Execution can be solved by ranging over the ticker channel. The contents
> of the loop will be run for each input received from the ticker channel. If
> the loop executes in less than one period, the loop will execute every
> period.
>
> Since tickers use channels, the execution loop can be run anywhere, though
> they are frequently used in goroutines because the program is also doing
> something else.
>
> I would simplify Rodolfo’s examples to:
>
> package main
>
> import (
> "fmt"
> "time"
> )
>
> func square(x int) int {
> return x * x
> }
>
> func cube(x int) int {
> return x * x * x
> }
>
> func main() {
> ticker := time.NewTicker(5 * time.Second)
>
> for range ticker.C {
> fmt.Println(square(10))
> fmt.Println(cube(10))
> }
> }
>

don't forget to add a 'defer ticker.Stop()' :)
(especially in examples that might be copy-pasted)

-s


>
> This will run square and cube every 5 seconds while the program is
> executing.
>
> On Thursday, February 23, 2017 at 2:39:12 AM UTC+1, Keith Brown wrote:
>>
>> Oddly, I can't find a single example on the world wide web for what I am
>> trying to do.
>>
>> I have 2 functions which I want to run on a periodic basis. The functions
>> are square and cube.
>> Here is my code so far. https://play.golang.org/p/akMxcg2Sra
>> But, I am not sure how to schedule these functions.  I looked here,
>> https://gobyexample.com/tickers, but really isn't that helpful or
>> intuitive.
>>
>>
>>
>> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to