Skip to content

Instantly share code, notes, and snippets.

@Ammar-64
Forked from Kishimoto96/cronandsockets.md
Last active June 10, 2023 12:19
Show Gist options
  • Save Ammar-64/9463e95e3d288e93d4d9569bbd98ec3c to your computer and use it in GitHub Desktop.
Save Ammar-64/9463e95e3d288e93d4d9569bbd98ec3c to your computer and use it in GitHub Desktop.

Discussion about Cron and Websockets:

  1. What is a cron job?
  2. Is it possible to specify a time zone when scheduling a task with cron?
  3. What happens if a cron job takes longer than expected to complete its execution? Will another instance start running while the first one is still executing?
  4. What is a websocket?
  5. What is the advantage of using WebSockets over traditional HTTP requests?
  6. What is Socket.IO?
  7. What do we mean by websocket handshake?
  8. What is redis?
  9. What is the purpose of using redis?
  10. Give 3 examples of applications that use redis?
  11. What is Design pattern in programming?
  12. what are the main three categories of design pattern?
  13. What are some benefits of using design pattern?
@sncey
Copy link

sncey commented Jun 10, 2023

@Irzooqi @jimaa-maya @nourkrimesh @tomiece317

1- A cron job is a scheduling feature in Unix-like systems that automates the execution of scripts or commands at specific intervals or dates. It allows users to define tasks and their desired timing in a crontab file. The cron daemon then checks the file regularly and runs the scheduled tasks accordingly. Cron jobs are commonly used for automating repetitive tasks and system maintenance. It allows you to automate repetitive tasks or execute commands/scripts at predetermined times without manual intervention. Users who set up and maintain software environments use cron to schedule jobs, also known as cron jobs, to run periodically at fixed times, dates, or intervals.

2- No, cron does not have a built-in feature to specify a time zone when scheduling tasks. However, you can adjust the system's time zone or modify the commands or scripts to handle time zone conversions if needed. But also you can say yes, it is possible to specify a time zone when scheduling a task with cron. If you can specify the time zone for CRON by setting the TZ environment variable in the crontab file.

3- No, cron does not run another instance of a job if the previous instance is still executing. Each job is executed sequentially, ensuring that the next instance does not start until the previous one completes. Cron just ends up spawning more and more copies of the script. The behavior of cron jobs in such a situation depends on the specific implementation and configuration. By default, cron jobs do not overlap. If a cron job is still running when its next scheduled execution time arrives, the subsequent instance of the job will not start until the previous one has completed.

4- WebSocket is a communication protocol that enables real-time, bidirectional communication between a client and a server over a single TCP connection. It allows efficient, low-latency data exchange for interactive web applications. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011. The current API specification allowing web applications to use this protocol is known as WebSockets. Unlike traditional web communication protocols such as HTTP, which follow a request-response model, WebSockets allow both the client and server to initiate communication and send data to each other asynchronously.

5- The advantage of using WebSockets over traditional HTTP requests is that WebSockets provide persistent, full-duplex communication channels between the client and server. Unlike HTTP, which relies on request-response interactions, WebSockets enable real-time, bi-directional data exchange without the need for repeated requests. This results in lower latency, reduced overhead, and more efficient communication, making WebSockets ideal for real-time applications that require instant updates and interactive data exchange. Websockets are typically faster than HTTP because they allow for real-time, bidirectional communication and reduce overhead by eliminating the need for new HTTP requests.

6- Socket.IO is a JavaScript library that enables real-time, bidirectional communication between clients and servers. It simplifies the implementation of real-time applications by providing a WebSocket abstraction layer with additional features like event-based communication and automatic reconnection handling.

7- WebSocket handshake is the initial process where a client and server establish a WebSocket connection. It involves an HTTP-based exchange where the client requests an upgrade to the WebSocket protocol, and the server confirms the upgrade, allowing bidirectional communication. Handshaking is the basic concept of Web Socket protocol.

8- Redis (Remote Dictionary Server) is a high-performance, open-source, in-memory data store used as a database, cache, or message broker. It offers a variety of data structures, fast data access, and advanced features like replication and pub/sub messaging. Redis is widely used for caching, real-time applications, and scalable data storage. Redis is an in-memory data structure store, used as a distributed, in-memory key–value database, cache and message broker, with optional durability. Redis supports different kinds of abstract data structures, such as strings, lists, maps, sets, sorted sets, HyperLogLogs, bitmaps, streams, and spatial indices.

9- Redis is used for caching, real-time applications, session storage, queues, pub/sub messaging, and data persistence. It provides high performance, scalability, and various features that cater to diverse data storage and processing needs. Redis enables you to write traditionally complex code with fewer, simpler lines. With Redis, you write fewer lines of code to store, access, and use data in your applications. The difference is that developers who use Redis can use a simple command structure as opposed to the query languages of traditional databases.

10- 3 examples of applications that use redis:
Twitter: Twitter uses Redis for real-time trending topics and analytics. It caches frequently accessed data, such as user timelines and tweets, to enhance performance and reduce the load on backend systems.

Airbnb: Airbnb utilizes Redis for caching and session storage. It caches search results, property listings, and user data to provide faster and more responsive user experiences. Redis is also used for session management to handle user authentication and personalization.

Uber: Uber uses Redis for various purposes, including real-time geospatial data storage and analysis. It stores driver and rider location data, performs real-time calculations for matching drivers with riders, and tracks live updates during trips, all of which contribute to the real-time nature of the Uber platform.

11- Design patterns in programming are reusable solutions to common software design problems. They provide established guidelines and best practices for structuring code, improving maintainability and scalability. By following design patterns, developers can leverage proven solutions and promote efficient, modular, and flexible software development.

12- The main three categories of design patterns are:

Creational Patterns: These patterns focus on object creation mechanisms, providing ways to create objects in a flexible and controlled manner. Examples include Factory Method, Singleton, and Builder patterns.

Structural Patterns: These patterns deal with the composition of classes and objects to form larger structures while keeping them flexible and efficient. Examples include Adapter, Decorator, and Composite patterns.

Behavioral Patterns: These patterns focus on the interaction and communication between objects, defining how they collaborate to achieve common goals. Examples include Observer, Strategy, and Command patterns.

13- Using design patterns in software development brings benefits such as code reusability, maintainability, scalability, optimized performance, and improved communication among developers. They provide proven solutions, promote best practices, and enhance the overall quality of the codebase.

@Mustapha909
Copy link

@sheidanouri @irodamrj Nezir Aydin
1- Cron is a utility program that lets users input commands for scheduling tasks repeatedly at a specific time. Tasks scheduled in cron are called cron jobs.
2- Users can determine what kind of task they want to automate and when it should be executed.
3- They'll run at the same time. The standard practice around this is to create a file lock (commonly referred to as a flock), and if the lock isn't available, don't run.
4- The WebSocket API is an advanced technology that makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.
WebSocket is bidirectional, a full-duplex protocol that is used in the same scenario of client-server communication, unlike HTTP it starts from ws:// or wss://. It is a stateful protocol, which means the connection between client and server will keep alive until it is terminated by either party (client or server). After closing the connection by either of the client and server, the connection is terminated from both ends.
5- allow for real-time, bidirectional communication and reduce overhead by eliminating the need for new HTTP requests.
6- Socket.IO is an event-driven library for real-time web applications. It enables real-time, bi-directional communication between web clients and servers. It consists of two components: a client, and a server. Both components have a nearly identical API.
Socket.IO enables real-time bidirectional event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed. Socket.IO is built on top of the WebSockets API (Client side) and Node.js. It is one of the most depended upon library on npm (Node Package Manager).
7- In literal terms, handshaking can be defined as gripping and shaking of right hands by two individuals, as to symbolize greeting, congratulations, agreement or farewell. In computer science, handshaking is a process that ensures the server is in sync with its clients. Handshaking is the basic concept of Web Socket protocol.
8- The open-source, in-memory data store used by millions of developers as a database, cache, streaming engine, and message broker.
9- Redis enables you to write traditionally complex code with fewer, simpler lines.
10- Twitter, Udemy, Airbnb, Instagram.
11- formalized best practices that the programmer can use to solve common problems when designing an application or system. Design patterns provide a standard terminology and are specific to particular scenario.
12- creational structural and behavioral.
13- Advantage of design pattern:
-They are reusable in multiple projects.
-They provide the solutions that help to define the system architecture.
-They capture the software engineering experiences.
-They provide transparency to the design of an application.

@OmarQaqish
Copy link

OmarQaqish commented Jun 10, 2023

@aydinfz @abdulsalamhamandoush @OmarQaqish Khaled Naes

  1. A cron job is a time-based job scheduler in Unix-like operating systems. It allows users to schedule and automate the execution of commands or scripts at specified intervals or specific times. Cron jobs are typically used for recurring tasks such as system maintenance, backups, or running regular scripts. They are configured using the cron daemon, which runs in the background and triggers the scheduled jobs based on predefined schedules.

  2. By default, cron uses the UTC time zone for scheduling tasks. However, it is possible to specify a specific time zone when scheduling a task with cron.

  3. If a cron job takes longer than expected to complete, the next instance of the job will not start until the previous one finishes. Cron jobs do not overlap by default and rely on locking mechanisms to prevent concurrent execution.

  4. WebSocket is a communication protocol that enables full-duplex communication between a client and a server over a single, long-lived connection. It allows for real-time, bidirectional data exchange without the need for repeated requests or polling. WebSocket is well-suited for applications requiring instant updates or real-time interactions, such as chat applications or live data streaming. It establishes a persistent connection between the client and server, facilitating efficient and low-latency communication.

  5. WebSockets are typically faster than HTTP because they allow for real-time, bidirectional communication and reduce overhead by eliminating the need for new HTTP requests. WebSockets have multiple advantages over HTTP requests, allowing for:

  • Real-time communication
  • Reduced overhead
  • Improved performance
  • Lower resource consumption
  • Bi-directional communication
  • Scalability
  • Server-initiated updates: Unlike traditional HTTP, where the client must initiate a request to the server for updates, WebSockets enable the server to push data to the client proactively. This server-initiated communication allows for instant updates and real-time notifications.
  1. Socket.IO is a JavaScript library that enables real-time, bidirectional communication between a client and a server. It provides a layer of abstraction on top of WebSockets and offers additional features to facilitate real-time communication. Socket.io has two parts: client-side and server-side. Both parts have an identical API:
    The server-side library runs in node.js.
    The client-side library runs in the browser.

  2. The handshake is the "Web" in WebSockets. It's the bridge from HTTP to WebSockets. In the handshake, details of the connection are negotiated, and either party can back out before completion if the terms are unfavorable. The server must be careful to understand everything the client asks for, otherwise security issues can occur.
    server

  3. Redis (for REmote DIctionary Server) is an open source, in-memory, NoSQL key/value store that is used primarily as an application cache or quick-response database. Because it stores data in memory, rather than on a disk or solid-state drive (SSD), Redis delivers unparalleled speed, reliability, and performance. Redis supports different kinds of abstract data structures, such as strings, lists, maps, sets, sorted sets, HyperLogLogs, bitmaps, streams, and spatial indices.

  4. The purpose of using Redis is to leverage its speed, versatility, and various data structures to enhance performance, scalability, and real-time capabilities in applications, whether as a cache, data store, message broker, or other use cases that benefit from fast and efficient data manipulation.

  5. Twitter, GitHub, Snapchat, StackOverFlow.

  6. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system. They are solutions that solve a recurring problem within a given context.

  7. Creational Design Pattern, Structural Design Pattern, and Behavioral Design Pattern.

  • Design patterns help you analyze the more abstract areas of a program by providing concrete, well-tested solutions.
  • Design patterns help you write code faster by providing a clearer picture of how you are implementing the design.
  • Design patterns encourage code reuse and accommodate change by supplying well-tested mechanisms for delegation and other non-inheritance based reuse techniques.
  • Design patterns encourage more legible and maintainable code by following well-understood paths.
  • Design patterns increasingly provide a common language for programmers.

@omikay
Copy link

omikay commented Jun 10, 2023

@omikay | @baraah-berra | @ramin

  1. a cron job is a repetitive program run periodically based on a specific schedule.
  2. Yes. To use cron with timezone, you can:
  • Set your system's time zone to the intended time zone and then state the time for that zone in the cron job.
  • Specify a timezone for your whole cron file by setting a timezone as CRON_TZ=UTC, or any other timezone listed by timedatectl list-timezones.
  1. If a job takes longer than expected, then the next one is delayed. Quoting from Wiki If your function execution takes longer than the timer interval, another execution won't be triggered until after the current invocation completes. The next execution is scheduled after the current execution completes.
  2. WebSocket is a computer communications protocol providing full-duplex (A full-duplex (FDX) system allows communication in both directions and, unlike half-duplex, allows this to happen simultaneously.) communication channels over a single TCP connection. It is a stateful protocol, which means the connection between client and server will stay alive until it is terminated by either party (client or server). After closing the connection by either the client or server, the connection is terminated from both ends.
  3. HTTP is unidirectional, where the client sends the request, and the server sends the response. Almost all real-time applications like (trading, gaming, monitoring, and notification) services use WebSocket to receive the data on a single communication channel. All the frequently updated applications used WebSocket because it is faster than HTTP Connection.

If we want to fetch old data or want to get the data only once to process it with an application, we should go with the HTTP protocol. These old data are not required very frequently or fetched only once and can be queried by a simple HTTP request, so in this scenario, it’s better not to use WebSocket.
6. socket.io, a widely adopted JavaScript library, provides a seamless and efficient solution for implementing real-time communication in web applications.
7. The handshake is the "Web" in WebSockets. It's the bridge from HTTP to WebSockets. In the handshake, details of the connection are negotiated, and either party can back out before completion if the terms are unfavorable. The server must be careful to understand everything the client asks for; otherwise, security issues can occur.
8. Redis is an open-source, in-memory, key-value data store most commonly used as a primary database, cache, message broker, and queue. Redis delivers sub-millisecond response times, enabling fast and powerful real-time applications in industries such as gaming, fintech, ad-tech, social media, healthcare, and IoT.
9.

  • Performance: Redis runs in-memory and enables low-latency and high throughput. It supports millions of operations per second.
  • Replication: Redis offers asynchronous replication and Active-Active Geo-Distribution to ensure that data is available for both reads and writes. It also supports point-in-time backups.
  • Caching: Redis is used as a cache in almost every application to reduce the load on a relational or NoSQL database.
  • Simplicity: Redis makes complex applications easier to write and maintain. It provides clients for almost every popular language, making it easy to build applications that can run on any platform.
  • Flexible data structures​: Strings, Hashes, Lists, Sets, Sorted Sets, Bitmaps, HyperLogLogs, Geospatial, Streams are all data types that can be used in Redis. They can be used for queues, latest updates, and geosearching.
  • Caching Systems: Redis is often used as an in-memory cache due to its high performance and low latency. Applications that handle large volumes of data or frequently accessed data can utilize Redis to store the most frequently accessed data in memory, reducing the load on backend databases and improving overall system performance. For example, popular content management systems like WordPress use Redis for object caching to speed up page rendering.
  • Real-time Data Streaming: Redis has features that make it suitable for real-time data streaming applications. It offers publish/subscribe messaging capabilities, allowing multiple clients to subscribe to channels and receive real-time updates. This makes it useful for building applications like chat systems, real-time analytics, and live streaming platforms. For instance, popular messaging platforms like Slack use Redis for real-time message delivery.
  • Job Queues and Background Processing: Redis provides data structures and commands that are well-suited for building job queues and managing background tasks. It allows applications to add tasks to a queue, process them asynchronously, and track the status of tasks. This is particularly useful in scenarios where time-consuming or resource-intensive tasks need to be offloaded from the main application flow. A popular example of an application using Redis for job queuing is Resque, a background job framework for Ruby on Rails.
  1. A design pattern in programming is a reusable solution to a commonly occurring problem in software design. It is a general, proven approach that provides a template for solving a particular design or implementation issue. Design patterns typically address specific concerns within the overall architecture of an application, such as object creation, structuring relationships between objects, managing communication between components, or organizing the flow of control. They provide a higher-level abstraction and promote loose coupling between components, making the code more flexible and adaptable to changes.
  • Creational Patterns: These patterns deal with object creation mechanisms, providing flexibility in creating objects without directly coupling the code to their specific classes or implementation. Examples include the Singleton pattern, Factory pattern, and Builder pattern.
  • Structural Patterns: Structural patterns focus on how objects are composed to form larger structures or entities while keeping the relationships between objects flexible. Patterns such as Adapter, Decorator, and Composite fall into this category.
  • Behavioral Patterns: Behavioral patterns are concerned with communication and interaction between objects, defining common communication patterns, and the assignment of responsibilities. Examples include Observer, Strategy, and Template Method patterns.
  1. Reusability: Design patterns provide reusable solutions to common problems. Once a pattern is established and well-documented, it can be applied across different projects and scenarios. This saves development time and effort by avoiding the need to reinvent solutions to known problems.

Maintainability: Design patterns promote modular and organized code structures. They provide clear guidelines for separating concerns, establishing relationships between components, and defining responsibilities. This improves code readability and maintainability, as it becomes easier to understand and modify the codebase when following a well-known pattern.

Scalability: Design patterns help in building scalable applications. They provide abstraction and decoupling, allowing individual components to be modified or replaced without affecting the entire system. This modular approach facilitates the addition of new features or the adaptation to changing requirements, making the software more flexible and scalable.

Code Quality: Design patterns embody best practices and proven solutions to common problems. By following these patterns, developers can create more robust and reliable code. Design patterns promote concepts such as loose coupling, high cohesion, and separation of concerns, leading to cleaner, more understandable, and better-structured code.

Collaboration and Communication: Design patterns provide a common language and shared vocabulary among developers. They serve as a means of communication, allowing team members to understand and discuss the system's design using recognized patterns. This improves collaboration, eases knowledge transfer, and enhances teamwork.

Performance Optimization: Some design patterns, such as the Flyweight pattern or Proxy pattern, are specifically aimed at optimizing performance. These patterns provide techniques to manage resources efficiently, reduce memory usage, minimize network requests, or avoid unnecessary computations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment