You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将简单Go脚本作为Android后台服务运行?

Running Your Go News-Fetcher as a Background Service

Alright, let's get your Go app running as a persistent background service. First, we'll fix up your code to avoid common pitfalls like infinite spam requests and resource leaks, then walk through setting it up as a service across major operating systems.

Step 1: Fix the Core Code

Your original code has a few gaps—missing imports, no request throttling, and incomplete error handling. Here's the polished version:

package main

import (
    "io/ioutil"
    "log"
    "net/http"
    "strings"
    "time"

    "golang.org/x/mobile/app"
)

func main() {
    app.Main(func(a app.App) {
        // Use a ticker to control request frequency (adjust interval as needed)
        ticker := time.NewTicker(5 * time.Minute)
        defer ticker.Stop()

        for range ticker.C {
            req, err := http.NewRequest(
                "GET",
                "http://0.0.0.0:88/fetch_news",
                strings.NewReader("topic.title"),
            )
            if err != nil {
                log.Printf("Failed to create request: %v", err)
                continue
            }

            // Add a timeout to prevent hanging requests
            cli := &http.Client{Timeout: 10 * time.Second}
            res, err := cli.Do(req)
            if err != nil {
                log.Printf("Request failed: %v", err)
                continue
            }

            // Always close the response body to avoid resource leaks
            defer res.Body.Close()

            body, err := ioutil.ReadAll(res.Body)
            if err != nil {
                log.Printf("Failed to read response: %v", err)
                continue
            }

            log.Printf("Fetched news successfully! Response size: %d bytes", len(body))
        }
    })
}

Key Improvements:

  • Added missing strings and ioutil imports
  • Used a time.Ticker to avoid spamming your /fetch_news endpoint non-stop (adjust the 5-minute interval to fit your needs)
  • Added a client timeout to prevent the app from hanging on unresponsive requests
  • Improved error logging to make debugging easier
  • Ensured the response body is always closed to avoid resource leaks

Step 2: Compile the App

First, build the executable for your operating system:

# Linux/macOS
go build -o testapp testapp.go

# Windows
go build -o testapp.exe testapp.go

Step 3: Deploy as a Background Service

Linux (systemd)

Systemd is the standard service manager on most modern Linux distros. Create a service file at /etc/systemd/system/testapp.service:

[Unit]
Description=Background News Fetcher Service
After=network.target

[Service]
User=your_username  # Replace with your actual username
ExecStart=/full/path/to/testapp  # Replace with your executable path
Restart=always      # Auto-restart if the app crashes
RestartSec=5        # Wait 5 seconds before restarting
StandardOutput=journal+console
StandardError=journal+console

[Install]
WantedBy=multi-user.target

Then run these commands to enable and start the service:

sudo systemctl daemon-reload
sudo systemctl enable testapp.service
sudo systemctl start testapp.service

Check logs with:

journalctl -u testapp.service -f

macOS (Launchd)

Launchd handles background services on macOS. Create a plist file at ~/Library/LaunchAgents/com.yourname.testapp.plist (replace yourname with your identifier):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.yourname.testapp</string>
    <key>ProgramArguments</key>
    <array>
        <string>/full/path/to/testapp</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/var/log/testapp.log</string>
    <key>StandardErrorPath</key>
    <string>/var/log/testapp.log</string>
</dict>
</plist>

Load and start the service:

launchctl load ~/Library/LaunchAgents/com.yourname.testapp.plist
launchctl start com.yourname.testapp

View logs with:

tail -f /var/log/testapp.log

Windows (Windows Service)

Use the Non-Sucking Service Manager (nssm) to register your app as a Windows service (it's more user-friendly than built-in tools):

  1. Download nssm and place it in your system PATH or the same directory as your app.
  2. Open Command Prompt as Administrator, then run:
nssm install TestApp
  1. In the pop-up window:
    • Path: Select your testapp.exe file
    • Working Directory: Choose the folder containing your executable
    • Optional: Go to the Details tab to set log paths for stdout/stderr
  2. Click Install Service, then start it with:
net start TestApp

You can manage the service via the Windows Services Manager or using nssm commands.

内容的提问来源于stack exchange,提问作者tarmek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:34:54