diff --git a/README.md b/README.md index e13331f..56e24e3 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ Create a file `.digitalocean-dynamic-ip.json` (dot prefix to hide the file) and ```json { + "interval": "30m", "apikey": "samplekeydasjkdhaskjdhrwofihsamplekey", "doPageSize": 20, "useIPv4": true, @@ -90,13 +91,3 @@ By default the tool will not output anything on success. If you wish to see debu #run: ./digitalocean-dynamic-ip -debug /path/to/my/config.json ``` - -You can either set this to run periodically with a cronjob or use your own method. - -```bash -# run `crontab -e` to edit your crontab -# sample cron job task - -# m h dom mon dow command -*/5 * * * * /home/user/digitalocean-dynamic-dns-ip/digitalocean-dynamic-ip -``` diff --git a/digitalocean-dynamic-ip.go b/digitalocean-dynamic-ip.go index 987d1df..c2372ec 100644 --- a/digitalocean-dynamic-ip.go +++ b/digitalocean-dynamic-ip.go @@ -12,7 +12,10 @@ import ( "net/http" "net/url" "os" + "os/signal" "strconv" + "syscall" + "time" ) func checkError(err error) { @@ -48,6 +51,7 @@ var config ClientConfig // ClientConfig : configuration json type ClientConfig struct { + Interval string `json:"interval"` APIKey string `json:"apiKey"` DOPageSize int `json:"doPageSize"` UseIPv4 *bool `json:"useIPv4"` @@ -366,8 +370,9 @@ func toIPv6String(ip net.IP) (currentIP string) { // return true // } -func main() { - config = GetConfig() +// updateAllDomains retrieves the current IP addresses and loops through all +// domains in the config to update them with the current IPs. +func updateAllDomains(config ClientConfig) { currentIPv4, currentIPv6 := CheckLocalIPs() if currentIPv4 == nil && currentIPv6 == nil { logError("Current IP addresses are not valid, or both are disabled in the config. Check your configuration and internet connection.") @@ -379,3 +384,30 @@ func main() { log.Printf("%s: END", domain.Domain) } } + +func main() { + config = GetConfig() + + interval, err := time.ParseDuration(config.Interval) + checkError(err) + + ticker := time.NewTicker(interval) + cancelChan := make(chan os.Signal) + signal.Notify(cancelChan, syscall.SIGTERM, syscall.SIGINT) + + // Run once immediately before waiting for the ticker + updateAllDomains(config) + + func() { + for { + select { + case <-cancelChan: + return + case <-ticker.C: + updateAllDomains(config) + } + } + }() + + ticker.Stop() +} diff --git a/digitalocean-dynamic-ip.sample.json b/digitalocean-dynamic-ip.sample.json index df9b471..ede7b88 100644 --- a/digitalocean-dynamic-ip.sample.json +++ b/digitalocean-dynamic-ip.sample.json @@ -1,4 +1,5 @@ { + "interval": "30m", "apikey": "samplekeydasjkdhaskjdhrwofihsamplekey", "doPageSize": 20, "useIPv4": true,