EXAMPLE #10
PHP
Bash
Long-running interval reporter
A daemon that emits a heartbeat event every N seconds.
10-continuous-reporter.php
#!/usr/bin/env php
<?php
/**
* Example: Continuous event reporter (daemon-style)
*
* Runs in a loop and sends an event at a regular interval. Useful for
* long-running processes that report metrics continuously, such as a
* queue worker reporting job counts or a service reporting health.
*
* Usage:
* php 10-continuous-reporter.php
*
* Stop with Ctrl+C.
*/
$baseUrl = 'https://www.spaceplace.app';
$dataStreamId = 'YOUR-DATASTREAM-UUID-HERE';
$tokenValue = 'YOUR-TOKEN-VALUE-HERE';
$intervalSec = 60; // report every 60 seconds
echo "Starting continuous reporter (every {$intervalSec}s). Press Ctrl+C to stop.\n\n";
while (true) {
// Collect a metric -- replace this with your real data collection
$metric = [
'number' => rand(0, 100),
'source' => gethostname(),
'key' => 'heartbeat',
'value' => 'alive',
];
$ch = curl_init("{$baseUrl}/api/events");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Accept: application/json',
"X-DataStream-ID: {$dataStreamId}",
"X-Token: {$tokenValue}",
],
CURLOPT_POSTFIELDS => json_encode($metric),
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$time = date('Y-m-d H:i:s');
if ($httpCode === 201) {
$body = json_decode($response, true);
echo "[{$time}] Sent heartbeat (Event: {$body['event_id']})\n";
} else {
echo "[{$time}] Failed (HTTP {$httpCode})\n";
}
sleep($intervalSec);
}
10-continuous-reporter.sh
#!/usr/bin/env bash
#
# Example: Continuous event reporter (daemon-style)
#
# Runs in a loop and sends an event at a regular interval.
#
# Usage:
# bash 10-continuous-reporter.sh
#
# Stop with Ctrl+C.
BASE_URL="https://www.spaceplace.app"
DATASTREAM_ID="YOUR-DATASTREAM-UUID-HERE"
TOKEN_VALUE="YOUR-TOKEN-VALUE-HERE"
INTERVAL=60 # seconds
echo "Starting continuous reporter (every ${INTERVAL}s). Press Ctrl+C to stop."
echo ""
while true; do
number=$((RANDOM % 101))
hostname=$(hostname)
response=$(curl -s -w "\n%{http_code}" \
-X POST "${BASE_URL}/api/events" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "X-DataStream-ID: ${DATASTREAM_ID}" \
-H "X-Token: ${TOKEN_VALUE}" \
-d "{
\"number\": ${number},
\"source\": \"${hostname}\",
\"key\": \"heartbeat\",
\"value\": \"alive\"
}")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
ts=$(date '+%Y-%m-%d %H:%M:%S')
if [ "$http_code" = "201" ]; then
event_id=$(echo "$body" | jq -r '.event_id')
echo "[${ts}] Sent heartbeat (Event: ${event_id})"
else
echo "[${ts}] Failed (HTTP ${http_code})"
fi
sleep "$INTERVAL"
done