How to build a cron system for automatic match monitoring?

What is a cron system for monitoring sports matches

A cron system is a set of regular background tasks on a server that run scripts on a schedule. In the context of sports analytics, cron is used to periodically call the sports events API, retrieve updates on matches, and automatically refresh data in your services: live centers, betting applications, analysts’ dashboards.

A typical scenario looks like this: cron calls your script every N seconds or minutes. The script accesses the sports API, for example, to the endpoint /v2/football/matches based on 2. api.api-sport.ru, receives a list of matches with the current status, minute, score, live events, and bookmaker odds. The data is then saved to the database and used for display on the website, model calculations, or triggering notifications to users.

Based on such a scheme, a robust monitoring system can be built for different sports: football, hockey, basketball, tennis, table tennis, and esports. The cron approach is especially convenient when there is no WebSocket integration yet or when you want to have full control over the request frequency. In this case, the data provider plays a key role: the quality and completeness of the API affect the accuracy and speed of your platform’s updates.

How to choose a sports events API for automatic monitoring

For the cron system to work reliably, you need to start not with cron, but with choosing the right API. Several parameters are important: the breadth of coverage by sports and tournaments, the depth of data for each match, the speed of live updates, the stability of the infrastructure, and the quality of documentation. For automatic monitoring, the presence of status markings for matches (status), the current minute (currentMatchMinute), score, live events, and betting odds is critical.

The platform by the sports events API api-sport.ru is precisely focused on such tasks. Through a single interface, you gain access to football, basketball, hockey, tennis, table tennis, and esports. Endpoints like /v2/{sportSlug}/matches allow filtering matches by date, tournaments, status, and teams. Detailed structures with lineups, statistics, live events (liveEvents), and bookmaker odds are supported through the field oddsBase. This simplifies the construction of both simple live widgets and complex risk management systems.

An additional advantage is the development of functionality. api-sport.ru Plans include WebSocket channels and AI tools for intelligent prompts and alerting. This means you can start with a classic cron system based on HTTP requests and then smoothly transition to a hybrid architecture without changing providers: WebSocket for instant updates and cron for background synchronization and backup routing.

What data can be obtained through the sports matches API

A modern sports API is not just about the score and match status. Through the endpoint /v2/{sportSlug}/matches based on 2. api.api-sport.ru you receive a structured match object with fields status, датаСобытия, startTimestamp, currentMatchMinute, data about the tournament and season, team lineups, and the stadium. For live matches, scores by periods are available (домашнийСчет, выезднойСчет), live events (liveEvents: goals, cards, substitutions, etc.) and detailed match statistics in an array. matchStatistics.

A separate layer of data includes bookmaker odds and bets. The field oddsBase contains betting markets (for example, a group 1X2 for the match outcome) and a set of options (choices) with current and starting odds, as well as change flags. This allows the cron system to track not only the progress of the game but also market dynamics: where the odds are rising, where they are falling, and which outcomes are blocked. Based on this information, it is easy to build signals for trading and risk management systems for bookmakers.

For deep monitoring scenarios, additional endpoints can be connected: /v2/{sportSlug}/matches/{matchId} for detailed data on a specific match with lineups and advanced statistics, /v2/{sportSlug}/matches/{matchId}/events for a chronological list of all events, /v2/{sportSlug}/players и /v2/{sportSlug}/teams for working with players and teams. This level of detail allows for the creation of advanced services: from production live centers to analytical AI models that use the full context of the match.

How to set up cron jobs for regular requests to the sports API

The most common environment for running a cron system is a Linux server. The scheduler cron allows you to set a schedule for script execution with minute precision. Before setting it up, make sure you have a working API key, which can be obtained at your personal account at api-sport.ru, and that your scripts correctly handle responses from the sports API and network errors.

The basic approach is to divide tasks by type and frequency. For example, preloading matches for the day across all interested tournaments can be done every 10-15 minutes. Live monitoring for matches with the status inprogress can be run more frequently — every 30-60 seconds, if API limits allow. The final synchronization (pulling statistics and final odds for completed matches) can be done every few minutes.

An example of a crontab file for a Python project might look like this:

# каждые 15 минут обновляем список матчей на сегодня
*/15 * * * * /usr/bin/python3 /var/www/project/fetch_schedule.py >> /var/log/cron-matches.log 2>&1
# каждые 30 секунд мониторим лайв-матчи (через * * * * * и внутренний цикл)
* * * * * /usr/bin/python3 /var/www/project/live_watcher.py >> /var/log/cron-live.log 2>&1

Inside the scripts, set additional timers and queues to stay within request limits. It is important to implement logging (of successes and errors), retries for temporary failures, as well as caching rarely changing entities (categories, tournaments, teams). As a WebSocket interface becomes available, api-sport.ru part of the cron load can be transferred to event subscriptions, leaving cron as a backup and aggregating circuit.

Examples of scripts for monitoring matches via API in Python and PHP

Let’s consider a practical example of a Python script that is used in a cron system for monitoring live matches. The script calls the endpoint /v2/football/matches with a filter by status inprogress, outputs basic information, and can be used as a basis for saving data to a database or generating notifications.

import requests
API_KEY = 'ВАШ_API_KEY'
BASE_URL = 'https://api.api-sport.ru/v2/football/matches'
headers = {
    'Authorization': API_KEY,
}
params = {
    'status': 'inprogress',
}
response = requests.get(BASE_URL, headers=headers, params=params)
response.raise_for_status()
data = response.json()
for match in data.get('matches', []):
    home = match['homeTeam']['name']
    away = match['awayTeam']['name']
    minute = match.get('currentMatchMinute')
    score_home = match['homeScore']['current']
    score_away = match['awayScore']['current']
    print(f"{match['id']}: {home} - {away}, {score_home}:{score_away}, {minute}'")

For PHP projects, the logic is similar. Below is an example of a script that can be run via cron. It retrieves a list of football matches for a specific tournament (through the parameter tournament_id) and saves JSON to a file for further processing or caching.

Such scripts can be easily adapted for other sports by changing only the parameter sportSlug in the URL: basketball, ice-hockey, tennis, table-tennis, esports. Thanks to a unified API response format, it is sufficient to implement the processing of basic structures once and reuse it for all disciplines.

How to process and save match data from the API to a database

After the cron system receives fresh data from the sports API, the next step is to save it correctly. It is important to design the database structure based on stable identifiers that come from 2. api.api-sport.ru. For matches, this field is идентификатор, for tournaments — tournament.id, for teams and players — their own идентификатор. Primary and foreign keys are built on these fields, allowing for safe record updates without duplicates.

The minimum set of tables for monitoring matches usually includes: матчи (basic information about the match and score), команды, турниры, события (live events from liveEvents or endpoint /matches/{matchId}/events), as well as the table шансы for storing coefficients from the array oddsBase. Below is an example of a simple match table schema in SQL.

CREATE TABLE matches (
    id              BIGINT PRIMARY KEY,
    sport_slug      VARCHAR(32) NOT NULL,
    tournament_id   BIGINT NOT NULL,
    category_id     BIGINT NOT NULL,
    date_event      DATE NOT NULL,
    start_ts        BIGINT NOT NULL,
    status          VARCHAR(32) NOT NULL,
    current_minute  INT,
    home_team_id    BIGINT NOT NULL,
    away_team_id    BIGINT NOT NULL,
    home_score      INT,
    away_score      INT,
    updated_at      TIMESTAMP NOT NULL DEFAULT NOW()
);

With each run of the cron script, use upsert operations (INSERT ON CONFLICT / REPLACE / MERGE depending on the DBMS) to update data for existing matches and add new ones. It is important to handle status changes (for example, не начато → в процессе → завершено) and not overwrite already recorded historical statistics. For events and odds, it makes sense to store the complete history: this will allow analyzing the dynamics of the line and building analytical models. This approach turns your cron monitoring into a reliable repository of sports data based on the API api-sport.ru.

How to set up notifications for goals and results based on sports API data

One of the most sought-after features of the cron system is instant notifications about key events: goals, red cards, the start and end of the match, sharp changes in odds. To implement such functionality, it is enough to compare the new state of the match obtained from the API with what is already saved in the database. If the score has changed, a new element has appeared in the array liveEvents or the status has become завершено, you can generate the corresponding notification.

Technically, this is implemented by a separate worker that runs via cron and processes only the latest changes. It can subscribe to the events table or store a «snapshot» of the previous state in the cache. Each time it runs, the worker fetches fresh data through the endpoints /v2/{sportSlug}/matches or /v2/{sportSlug}/matches/{matchId}/events, compares it with local data, and sends notifications through the selected channels: pushes in the app, emails, messengers, internal signals for traders and bookmakers’ analysts.

Below is an example of simplified logic in JavaScript-like pseudocode that can be executed in your backend after each update from the API.

function handleMatchUpdate(prev, current) {
  // гол
  if (current.homeScore.current !== prev.homeScore.current ||
      current.awayScore.current !== prev.awayScore.current) {
    sendGoalNotification(current);
  }
  // смена статуса
  if (current.status !== prev.status) {
    if (current.status === 'inprogress') sendMatchStartedNotification(current);
    if (current.status === 'finished') sendMatchFinishedNotification(current);
  }
  // резкое изменение коэффициентов
  if (hasSignificantOddsChange(prev.oddsBase, current.oddsBase)) {
    sendOddsAlert(current);
  }
}

As the WebSocket interface and AI tools appear on the platform api-sport.ru part of this logic can be transferred to stream processing: receiving events in real-time and immediately passing them through AI filters of importance, sending only truly valuable signals to users. However, even with the classic HTTP + cron API, this approach already allows building professional alerting systems based on reliable sports data.