|
| 1 | +# Using Cron Jobs in GoFr |
| 2 | + |
| 3 | +This example demonstrates how to schedule and run background jobs using the **GoFr** framework’s built-in Cron Job support. |
| 4 | + |
| 5 | +--- |
| 6 | + |
| 7 | +## Overview |
| 8 | + |
| 9 | +In this example, we: |
| 10 | + |
| 11 | +* Schedule a job named `counter` to run **every second**. |
| 12 | +* Increment a counter on each execution and log its value. |
| 13 | +* Run the application for a limited duration (3 seconds) to demonstrate the cron execution in action. |
| 14 | +* Include a unit test to verify that the cron job executes successfully. |
| 15 | + |
| 16 | +--- |
| 17 | + |
| 18 | +## How to Run |
| 19 | + |
| 20 | +1. **Clone the repository** and navigate to this example: |
| 21 | + |
| 22 | + ```bash |
| 23 | + git clone https://github.com/gofr-dev/gofr.git |
| 24 | + cd gofr/examples/using-cron-jobs |
| 25 | + ``` |
| 26 | + |
| 27 | +2. **Run the application**: |
| 28 | + |
| 29 | + ```bash |
| 30 | + go run main.go |
| 31 | + ``` |
| 32 | + |
| 33 | + * The counter will increment every second. |
| 34 | + * Application will stop automatically after 3 seconds. |
| 35 | + *(In a real-world application, you would call `app.Run()` to keep the cron running indefinitely.)* |
| 36 | + |
| 37 | +--- |
| 38 | + |
| 39 | +## How It Works |
| 40 | + |
| 41 | +### main.go |
| 42 | + |
| 43 | +```go |
| 44 | +app.AddCronJob("* * * * * *", "counter", count) |
| 45 | +``` |
| 46 | + |
| 47 | +* Schedules the `count` function to run every second. |
| 48 | +* Cron syntax here uses six fields (including seconds) — `"* * * * * *"` means “every second.” |
| 49 | + |
| 50 | +```go |
| 51 | +time.Sleep(duration * time.Second) |
| 52 | +``` |
| 53 | + |
| 54 | +* Stops the application after the `duration` (3 seconds) for demonstration purposes. |
| 55 | + |
| 56 | +### count Function |
| 57 | + |
| 58 | +* Acquires a write lock. |
| 59 | +* Increments the counter variable `n`. |
| 60 | +* Logs the current counter value. |
| 61 | + |
| 62 | +--- |
| 63 | + |
| 64 | +## Testing |
| 65 | + |
| 66 | +The test (`main_test.go`): |
| 67 | + |
| 68 | +* Runs the `main()` function. |
| 69 | +* Waits slightly longer than 1 second. |
| 70 | +* Checks if the counter has incremented exactly once. |
| 71 | +* Logs the metrics server host. |
| 72 | + |
| 73 | +Run the test: |
| 74 | + |
| 75 | +```bash |
| 76 | +go test -v |
| 77 | +``` |
| 78 | + |
| 79 | +Expected output: |
| 80 | + |
| 81 | +``` |
| 82 | +=== RUN Test_UserPurgeCron |
| 83 | +--- PASS: Test_UserPurgeCron (1.10s) |
| 84 | +PASS |
| 85 | +``` |
| 86 | + |
| 87 | +--- |
| 88 | + |
| 89 | +## Example Output |
| 90 | + |
| 91 | +When running `main.go`, you should see: |
| 92 | + |
| 93 | +``` |
| 94 | +INFO Count: 1 |
| 95 | +INFO Count: 2 |
| 96 | +INFO Count: 3 |
| 97 | +``` |
| 98 | + |
0 commit comments